Replace space with an underscore

Luke Berry picture Luke Berry · Mar 9, 2011 · Viewed 35.3k times · Source

I am trying to write something that will replace all the spaces in a string with an underscore.

What I have so far.

string space2underscore(string text)
{
    for(int i = 0; i < text.length(); i++)
    {
        if(text[i] == ' ')
            text[i] = '_';
    }
    return text;
}

For the most part this would work, if I was doing something like.

string word = "hello stackoverflow";
word = space2underscore(word);
cout << word;

That would output "hello_stackoverflow", which is just what I want.

However if I was to do something like

string word;
cin >> word;
word = space2underscore(word);
cout << word;

I would just get the first word, "hello".

Does anybody know a fix for this?

Answer

Blastfurnace picture Blastfurnace · Mar 9, 2011

You've got your getline issue fixed but I just wanted to say the Standard Library contains a lot of useful functions. Instead of a hand-rolled loop you could do:

std::string space2underscore(std::string text)
{
    std::replace(text.begin(), text.end(), ' ', '_');
    return text;
}

This works, it's fast, and it actually expresses what you are doing.