簡體   English   中英

如何使用 while 循環替換在字符串中出現多次的子字符串?

[英]How do I replace a substring that appears more than once in a string using a while loop?

我有一個字符串,其中包含我需要查找和替換的兩個相同的子字符串。

我使用了Contains()方法,如果子字符串只出現一次,該方法可以正常工作。

string test = "abc";

if (line.Contains(test))
{
    string newLine = line;

    while (line.Contains(test))
    { 
        newLine = newLine.Replace(test, "Hello");
    }
}

我基本上需要一些可以讓我擺脫循環的東西。 比如正則表達式中的nextMatch。

除非我誤解了,否則您正在嘗試替換所有測試實例? 只需這樣做:

line = line.Replace(test, "Hello")

不需要 while 或循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM