c# 在字符串中查找字符串的出现并将文本环绕匹配的字符
c# Find occurrences of string within a string and wrap text around the matching chars
拆分字符串,示例here
var hello = "Hello World";
我试图让结果成为“Hello World”,并在匹配的“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
var result = Regex.Replace(hello, "l", x => $"<span>{x}</span>");
您可以使用 string.Join()
Console.WriteLine(string.Join("<span>l</span>", words));
而不是
//No need to build resultString as well. That mean you can eliminate for loop
Console.WriteLine(resultString);
注意:这只是与您的问题一致的另一种方式。 @fuzzybear 或@ASh 提出的解决方案比我建议的更优雅。
string str = "Hello world";
string resulStr = str.Replace("l", "<span>l</span>", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(resulStr);
拆分字符串,示例here
var hello = "Hello World";
我试图让结果成为“Hello World”,并在匹配的“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
var result = Regex.Replace(hello, "l", x => $"<span>{x}</span>");
您可以使用 string.Join()
Console.WriteLine(string.Join("<span>l</span>", words));
而不是
//No need to build resultString as well. That mean you can eliminate for loop
Console.WriteLine(resultString);
注意:这只是与您的问题一致的另一种方式。 @fuzzybear 或@ASh 提出的解决方案比我建议的更优雅。
string str = "Hello world";
string resulStr = str.Replace("l", "<span>l</span>", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(resulStr);