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"
}