簡體   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