Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions PowerKit.Tests/Extensions/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Text;
using FluentAssertions;
using PowerKit.Extensions;
Expand Down Expand Up @@ -128,6 +129,34 @@ public void ToSnakeCase_Test()
"".ToSnakeCase().Should().Be("");
}

[Fact]
public void TrimPrefix_Test()
{
// Act & assert
"hello world".TrimPrefix("hello").Should().Be(" world");
"hello world".TrimPrefix("world").Should().Be("hello world");
"hello world".TrimPrefix("").Should().Be("hello world");
"hello".TrimPrefix("hello").Should().Be("");
"HELLO world".TrimPrefix("hello", StringComparison.OrdinalIgnoreCase).Should().Be(" world");
"HELLO world".TrimPrefix("hello").Should().Be("HELLO world");
"".TrimPrefix("hello").Should().Be("");
"hello hello".TrimPrefix("hello").Should().Be(" hello");
}

[Fact]
public void TrimSuffix_Test()
{
// Act & assert
"hello world".TrimSuffix("world").Should().Be("hello ");
"hello world".TrimSuffix("hello").Should().Be("hello world");
"hello world".TrimSuffix("").Should().Be("hello world");
"hello".TrimSuffix("hello").Should().Be("");
"hello WORLD".TrimSuffix("world", StringComparison.OrdinalIgnoreCase).Should().Be("hello ");
"hello WORLD".TrimSuffix("world").Should().Be("hello WORLD");
"".TrimSuffix("world").Should().Be("");
"hello hello".TrimSuffix("hello").Should().Be("hello ");
}

[Fact]
public void Truncate_Test()
{
Expand Down
18 changes: 18 additions & 0 deletions PowerKit/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,24 @@ public SecureString ToSecureString()
/// </summary>
public string ToSnakeCase() => str.SeparateWords('_').ToLowerInvariant();

/// <summary>
/// Removes the specified prefix from the beginning of the string, if present.
/// If the string does not start with <paramref name="prefix"/>, the original string is returned unchanged.
/// </summary>
public string TrimPrefix(
string prefix,
StringComparison comparison = StringComparison.Ordinal
) => str.StartsWith(prefix, comparison) ? str[prefix.Length..] : str;

/// <summary>
/// Removes the specified suffix from the end of the string, if present.
/// If the string does not end with <paramref name="suffix"/>, the original string is returned unchanged.
/// </summary>
public string TrimSuffix(
string suffix,
StringComparison comparison = StringComparison.Ordinal
) => str.EndsWith(suffix, comparison) ? str[..^suffix.Length] : str;

/// <summary>
/// Truncates the string to the specified maximum number of characters.
/// </summary>
Expand Down