1

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.

svick
  • 236,525
  • 50
  • 385
  • 514
Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153

5 Answers5

13

Use a regular expression, e.g.

var input = "a__b_c_____d__e_f__";
var output = Regex.Replace(input, "_+", "_");
Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • +1, I was about to link to [this answer](http://stackoverflow.com/a/206946/416627) with the same suggested modification. – Dave Rager Jul 23 '12 at 20:06
1

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,}", "_");
Pierluc SS
  • 3,138
  • 7
  • 31
  • 44
0
 var cleanString = Regex.Replace("a__b_c_____d__e_f__", "(_)+", "$1");
Gabe
  • 49,577
  • 28
  • 142
  • 181
-1

This should get you started.

cat file | perl -e "s/\_+/\_/g"
Moses
  • 327
  • 2
  • 10
  • +1 .. because it's same same regular expression and suggests that the poster continues the thinking .. although perhaps should just be a comment. –  Jul 23 '12 at 20:08
-1

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.

Kreg
  • 647
  • 1
  • 6
  • 17