Split string, example here
var hello = "Hello World";
I'm trying to get the result to be "Hello World" with spans around the matching "l"
string[] words = hello.ToLower().Split("l");
var resultString = "";
for (int i = 0; i < words.Length; i )
{
// now we have split the string how do find the missing 'l' and wrap a span around them
resultString = words[i].ToString();
}
// result is heo word
Console.WriteLine(resultString);
// Trying to get the result to be "He<span>l</span><span>l</span>o Wor<span>l<span>d
CodePudding user response:
var result = Regex.Replace(hello, "l", x => $"<span>{x}</span>");
CodePudding user response:
string str = "Hello world";
string resulStr = str.Replace("l", "<span>l</span>", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(resulStr);
CodePudding user response:
You can do it using string.Join()
Console.WriteLine(string.Join("<span>l</span>", words));
Instead of
//No need to build resultString as well. That mean you can eliminate for loop
Console.WriteLine(resultString);
Note: This is just an alternate way aligned to your question. The solution proposed by @fuzzybear or @ASh are more elegant than what I suggested.