Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用while循环替换字符串中多次出现的子字符串?_C# - Fatal编程技术网

C# 如何使用while循环替换字符串中多次出现的子字符串?

C# 如何使用while循环替换字符串中多次出现的子字符串?,c#,C#,我有一个字符串,其中包含我需要查找和替换的两个子字符串 我使用了Contains()方法,如果子字符串只出现一次,该方法就可以正常工作 string test = "abc"; if (line.Contains(test)) { string newLine = line; while (line.Contains(test)) { newLine = newLine.Replace(test, "Hello"); } } 我基本上需要的

我有一个字符串,其中包含我需要查找和替换的两个子字符串

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

string test = "abc";

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

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

我基本上需要的东西,可以打破我的循环。例如regex中的nextMatch。

除非我有误解,否则您正在尝试替换所有的测试实例? 只要这样做:

line = line.Replace(test, "Hello")
无需while或循环。

while(line.Contains(test))
更改为
while(newLine.Contains(test))