You can use the Regex.Replace()
. Something like that:
string str = "Hello WorLLd"; //Substitui só os 'l' e não o 'L'
str = Regex.Replace(str, "l", "EL", RegexOptions.IgnoreCase);
Console.WriteLine("My string: " + str);
For those who don’t like Regex
, found this solution in a response in the OS:
public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison = StringComparison.CurrentCultureIgnoreCase) {
StringBuilder sb = new StringBuilder();
int previousIndex = 0;
int index = str.IndexOf(oldValue, comparison);
while (index != -1) {
sb.Append(str.Substring(previousIndex, index - previousIndex));
sb.Append(newValue);
index += oldValue.Length;
previousIndex = index;
index = str.IndexOf(oldValue, index, comparison);
}
sb.Append(str.Substring(previousIndex));
return sb.ToString();
}
I put in the Github for future reference.
The secret is the enumeration StringComparison
in the IndexOf()
. Use:
ReplaceString("Hello WorLLd", "l", "EL")
There’s another response in the OS which is a little better by already being an extension method for string
and avoid a StringBuilder
. But the construction of while
with break
is unnecessary. The ideal would be to improve this, but it still seems to me a better solution anyway.
public static class StringExtensions {
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType) {
int startIndex = 0;
while (true) {
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
startIndex += newValue.Length;
}
return originalString;
}
}
I put in the Github for future reference.
@Cell for simple things the
RegEx
It’s very simple. It complicates a bit for more sophisticated wedding patterns. Although it’s not a seven-headed bug either. In cases where performance is importantRegex
can become a burden.– Maniero