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
  • 225,720
  • 49
  • 378
  • 501
Sergey Metlov
  • 24,666
  • 27
  • 90
  • 147

5 Answers5

13

Use a regular expression, e.g.

var input = "a__b_c_____d__e_f__";
var output = Regex.Replace(input, "_+", "_");
Brian Rasmussen
  • 112,408
  • 34
  • 217
  • 309
  • +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,038
  • 7
  • 30
  • 44
0
 var cleanString = Regex.Replace("a__b_c_____d__e_f__", "(_)+", "$1");
Gabe
  • 48,376
  • 28
  • 140
  • 179
-1

This should get you started.

cat file | perl -e "s/\_+/\_/g"
Moses
  • 327
  • 2
  • 9
  • +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
  • 16