Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace space with an underscore

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?

like image 537
Luke Berry Avatar asked Mar 09 '11 21:03

Luke Berry


2 Answers

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.

like image 157
Blastfurnace Avatar answered Nov 11 '22 16:11

Blastfurnace


The problem is that cin >> word is only going to read in the first word. If you want to operate on a whole like at a time, you should use std::getline.

For example:

std::string s;
std::getline(std::cin, s);
s = space2underscore(s);
std::cout << s << std::endl;

Also, you may want to check that you actually were able to read a line. You can do that like this:

std::string s;
if(std::getline(std::cin, s)) {
    s = space2underscore(s);
    std::cout << s << std::endl;
}

Finally, as a side note, you could probably write your function in a cleaner way. Personally I would write it like this:

std::string space2underscore(std::string text) {
    for(std::string::iterator it = text.begin(); it != text.end(); ++it) {
        if(*it == ' ') {
            *it = '_';
        }
    }
    return text;
}

Or for bonus points, use std::transform!

EDIT: If you happen to be lucky enough to be able to use c++0x features (and I know that's a big if) you could use lambdas and std::transform, which results in some very simple code:

std::string s = "hello stackoverflow";
std::transform(s.begin(), s.end(), s.begin(), [](char ch) {
    return ch == ' ' ? '_' : ch;
});
std::cout << s << std::endl;
like image 25
Evan Teran Avatar answered Nov 11 '22 17:11

Evan Teran