Skip to content

Commit

Permalink
add - Added character replacement extension
Browse files Browse the repository at this point in the history
---

We've added a new extension that lets you replace a character in a string.

---

Type: add
Breaking: False
Doc Required: False
Backport Required: False
Part: 1/1
  • Loading branch information
AptiviCEO committed Oct 16, 2024
1 parent 2ec253c commit 7da6b37
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Textify.Tests/General/TextToolsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1760,6 +1760,21 @@ public void TestIsPalindromeCase(string source, bool expected)
bool result = source.IsPalindrome(true);
result.ShouldBe(expected);
}

/// <summary>
/// Tests for character replacement
/// </summary>
[DataTestMethod]
[DataRow("Textyfy", 4, 'i', "Textify")]
[DataRow("Nytrocid", 1, 'i', "Nitrocid")]
[DataRow("", 0, 'A', "")]
[DataRow(null, 0, 'A', "")]
[Description("Querying")]
public void TestReplaceChar(string source, int idx, char character, string expected)
{
string result = source.ReplaceChar(idx, character);
result.ShouldBe(expected);
}
}

}
24 changes: 24 additions & 0 deletions Textify/General/TextTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1935,5 +1935,29 @@ public static bool IsPalindrome(this string target, bool caseSensitive = false)
// It's a palindrome
return true;
}

/// <summary>
/// Replaces a single character in a string with a new character
/// </summary>
/// <param name="source">Source string to process</param>
/// <param name="idx">Index of a character in which replacement is done</param>
/// <param name="replacement">Replacement character</param>
/// <returns>A modified string</returns>
/// <exception cref="Exception"></exception>
public static string ReplaceChar(this string source, int idx, char replacement)
{
// Sanity checks
if (string.IsNullOrEmpty(source))
return "";
if (idx < 0)
throw new Exception($"Specified index [{idx}] may not be less than zero");
if (idx >= source.Length)
throw new Exception($"Specified index [{idx}] may not be larger than the source string length [{source.Length}]");

// Replace the character in a specified index
char[] chars = source.ToCharArray();
chars[idx] = replacement;
return new(chars);
}
}
}

0 comments on commit 7da6b37

Please sign in to comment.