Sergey Metlov
Sergey Metlov

Reputation: 26291

Multiple replace

Have:

"a__b_c_____d__e_f__"

Need:

"a_b_c_d_e_f_"

ie: Replace all the "___" substrings (1 or more underscores) with "_" (single underscore) without loops.

Upvotes: 1

Views: 1607

Answers (5)

Kreg
Kreg

Reputation: 647

There are several ways to go about solving the issue, but I'm a little uncertain what you mean by "without loops"...

obviously you could use a loop such as:

while (myString.contains("__"))
    myString.replace("__", "_");

I think though that this is what you are saying you're trying to avoid... the catch is though, that I don't believe there is a solution that doesn't involve loops somewhere. The .contains method, as well as the .replace method both use loops in their implementations. To clarify, the following code would also work:

string outputStr = "";
bool underscore = false;
for(int i = 0; i < myString.length; ++i)
{
    if (myString[i] == '_')
    {
        if (underscore == false)
            outputStr += myString[i];
        underscore = true;
    }else outputStr += myString[i];
}

As you can see, this only uses one loop. While this is more efficient, (You would probably want to use a StringBuilder instead of a string for the outputStr variable, if efficiency were an issue) the point is that if you need to look through a string, you're going to have to use a loop, whether it's you who writes the loop or whether you are calling some other method that does it for you.

Upvotes: -1

Moses
Moses

Reputation: 327

This should get you started.

cat file | perl -e "s/\_+/\_/g"

Upvotes: -1

Gabe
Gabe

Reputation: 50493

 var cleanString = Regex.Replace("a__b_c_____d__e_f__", "(_)+", "$1");

Upvotes: 0

Pierluc SS
Pierluc SS

Reputation: 3176

You can achieve this by using RegularExpressions as follow

string str = "a__b_c_____d__e_f__";
string newStr = System.Text.RegularExpressions.Regex.Replace(str, "_{2,}", "_");

Upvotes: 1

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Use a regular expression, e.g.

var input = "a__b_c_____d__e_f__";
var output = Regex.Replace(input, "_+", "_");

Upvotes: 13

Related Questions