0

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"

}
4
Contributors
7
Replies
12
Views
7 Years
Discussion Span
Last Post by travism
Featured Replies
  • Here is another way to do it. [code] string space2underscore(string text) { for(int i = 0; i < text.length(); i++) { if( isspace(text[i]) ) text[i] = '_'; } return text; [/code] Read More

1

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;
0

Yes, :

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

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>

Edited by Clinton Portis: replace(bad habbit, another bad habbit);

0

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.

Edited by Ancient Dragon: n/a

0

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?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.