我试图编写一个函数来获取带空格的字符串并返回不带空格的字符串。
例如:
str = " a f ";
将被替换为“af”;
我的函数不起作用,它将字符串替换为:“af f”。
这是我的功能:
void remove_space(string& str) {
int len = str.length();
int j = 0, i = 0;
while (i < len) {
while (str.at(i) == ' ') i++;
str.at(j) = str.at(i);
i++;
j++;
}
}
int main ()
{
string str;
getline(cin, str);
remove_space(str);
cout << str << endl;
return 0;
}
任何帮助表示赞赏!