繁体   English   中英

如何使用C#替换字符串中的单词(首次出现的除外)

[英]How do I replace word in string except first occurrence using c#

如何使用C#替换字符串中的单词(首次出现的除外)

例如

string s= "hello my name is hello my name hello";

x替换hello

output should be string news = "hello my name is x my name x";

我尝试过效果很好

string originalStr = "hello my hello ditch hello";
        string temp = "hello";
        string str = originalStr.Substring(0, originalStr.IndexOf(temp) + temp.Length);
        originalStr = str + originalStr.Substring(str.Length).Replace(temp, "x");

我可以为上述代码使用正则表达式吗?

这将以一般模式完成:

var matchPattern = Regex.Escape("llo");
var replacePattern = string.Format("(?<={0}.*){0}", matchPattern);
var regex = new Regex(replacePattern);
var newText = regex.Replace("hello llo llo", "x");

如果只想匹配和替换整个单词,请相应地编辑模式:

var matchPattern = @"\b" + Regex.Escape("hello") + @"\b";

尝试这个:

string pat = "hello";
string tgt = "x";
string tmp = s.Substring(s.IndexOf(pat)+pat.Length);
s = s.Replace(tmp, tmp.Replace(pat,tgt));

tmp是原始字符串的子字符串,该字符串在第一次出现要替换的模式( pat )的末尾之后开始。 然后,我们在此子字符串中将pat替换为所需的值( tgt ),并使用此更新后的值替换原始字符串中的子字符串。

演示版

您需要正则表达式吗? 您可以使用这个小LINQ查询和String.Join

int wordCount = 0;
var newWords = s.Split()
    .Select(word => word != "hello" || ++wordCount == 1 ? word : "x");
string newText = string.Join(" ", newWords);

但是请注意,这会将所有空白(甚至制表符或换行符)替换为一个空格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM