0

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?

3
  • Look up regular expressions. Specifically, use a capturing group to capture your search word, then use a reference to that group during replacement. Related: stackoverflow.com/questions/26984428/… Commented Nov 24, 2021 at 17:19
  • code please? I am not very familiar with regular expression usage Commented Nov 24, 2021 at 17:31
  • Do you have to handle generic cases, or is your string well known? Commented Nov 24, 2021 at 17:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.