简体   繁体   中英

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

I have a string that contains the same two substrings that I need to find and replace.

I used the Contains() method which works fine if there is only one occurrence of the substring.

string test = "abc";

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

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

I basically need something that can break me out of the loop. Such as nextMatch in regex.

Unless I have misunderstood, you are trying to replace all instances of test in line? Just do this:

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

no while or loop needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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