I wrote the following function that takes a string with spaces and replaces the space with an underscore ( _ ). The function works, but I believe there is a less novice way of doing it. Anyone have any suggestions? BTW, this is written in Linux and compiled with G++.

#include <iostream>
using namespace std;

string space2underscore(string text)
{
int length = text.size();
int x = 0;
string fixed;

while (x != length) {
        string letter = text.substr(x, 1);
        if (letter == " ") {
           letter = "_";}
        fixed = fixed + letter;
        x = x + 1;
                    }

return fixed;
}

int main() {
string test = "this is a test";
string mytest = space2underscore(test);
cout << mytest << endl;
//  would print "this_is_a_test"

}

Recommended Answers

All 7 Replies

Here is another way to do it.

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

Yes, :

char space = ' ';
for(unsigned int i = 0; i < str.size(); i++){
    if(str[i] == space){ 
           str[i] = '_'
    }
}

Probably the most efficient method that I could think of (in terms of line of code) would probably be something like this:

#include<algorithm>
#include<cstring>

char line[] = "Dance, too much booty in the pants.";
int size = strlen(line);

replace(&line[0], &line[size], ' ', '_');


replace() from <algorithm>

Probably the most efficient method that I could think of (in terms of line of code) would probably be something like this:

the replace() function may make your code smaller, but efficiency is probably the same. Somebody has to loop through the string one character at a time. Whether you do it or replace() doesn't really change the efficiency of the program at all.

Probably the most efficient method that I could think of (in terms of line of code) would probably be something like this:

#include<algorithm>
#include<cstring>

char line[] = "Dance, too much booty in the pants.";
int size = strlen(line);

replace(&line[0], &line[size], ' ', '_');


replace() from <algorithm>

One thing I have trouble with in C++ is that if I have a string to pass to your function, how do I convert it for char?

use std::string's c_str() method

Thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.