Home > Software engineering >  How to replace words while keeping case?
How to replace words while keeping case?

Time:11-25

I have a string as such:

string myString = "String testing string replace"

I want to take that string and give the word string a style. So the final string would be:

myString = "<span class='myclass'>String</span> testing <span class='myclass'>string</span> replace"

How can I do that programmatically? So that both instances of the word string keep their case?

CodePudding user response:

Perhaps something like:

var myString2 = Regex.Replace(
  myString, 
  Regex.Escape("string"), 
  "<span class='myclass'>$0</span>",    
  RegexOptions.IgnoreCase
);

The pattern is just the string you want to replace, escapes so if it had any characters in it that mean something to Regex (like a period) they match exactly. When a match occurs the whole match is stored in variable $0. This variable can be used in the replacement, so when we specify IgnoreCase it means that first match is on String, which means the replacement $0 is String.. the second match is on string

CodePudding user response:

string myString = "String testing string replace";
string stringOut = "";
foreach (var word in myString.Split(new char[] { ' '}))
{
  stringOut  = $"<span class='myclass'>{word}</span> ";
}
Console.WriteLine(stringOut);
  • Related