Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
20 changes: 20 additions & 0 deletions PowerKit.Tests/Extensions/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,26 @@ namespace PowerKit.Tests.Extensions;

public class StringExtensionsTests
{
[Fact]
public void Replace_Test()
{
// Act & assert
"a1b2c3".Replace(ch => char.IsDigit(ch) ? '*' : ch).Should().Be("a*b*c*");
"hello".Replace(ch => ch).Should().Be("hello");
"".Replace(ch => ch).Should().Be("");
}

[Fact]
public void ReplaceWhiteSpace_Test()
{
// Act & assert
"hello world".ReplaceWhiteSpace('_').Should().Be("hello_world");
"hello\tworld\nfoo".ReplaceWhiteSpace('-').Should().Be("hello-world-foo");
"hello\u00A0world".ReplaceWhiteSpace(' ').Should().Be("hello world");
"helloworld".ReplaceWhiteSpace('_').Should().Be("helloworld");
"".ReplaceWhiteSpace('_').Should().Be("");
}

[Fact]
public void Reverse_Test()
{
Expand Down
29 changes: 29 additions & 0 deletions PowerKit/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security;
using System.Text;

Expand All @@ -13,6 +14,34 @@ internal static class StringExtensions
{
extension(string str)
{
/// <summary>
/// Replaces each character using the replacement produced by the provided selector.
/// </summary>
public string Replace(Func<char, char> getReplacement) =>
string.Create(
str.Length,
(str, getReplacement),
static (chars, source) =>
{
foreach (var (i, ch) in source.str.Index())
{
chars[i] = source.getReplacement(ch);
}
}
);

/// <summary>
/// Replaces each whitespace character using the replacement produced by the provided selector.
/// </summary>
public string ReplaceWhiteSpace(Func<char, char> getReplacement) =>
str.Replace(ch => char.IsWhiteSpace(ch) ? getReplacement(ch) : ch);

/// <summary>
/// Replaces each whitespace character with the specified replacement character.
/// </summary>
public string ReplaceWhiteSpace(char replacement) =>
str.ReplaceWhiteSpace(_ => replacement);

/// <summary>
/// Returns the string with the characters in reverse order.
/// </summary>
Expand Down