使用std::string
做
std::string a("123 ");
std::string b("123");
a.erase(std::remove_if(a.begin(), a.end(), ::isspace), a.end());
if (a == b)
std::cout << "Same";
通过using
带来的变化将是
using namespace std;
string a("123 ");
string b("123");
a.erase(remove_if(a.begin(), a.end(), ::isspace), a.end());
if (a == b)
cout << "Same";
通常建议不要使用using namespace std
。不要忘记包括<string>
和<algorithm>
。
编辑如果您仍然想这样做的C方式,从这个帖子
https://stackoverflow.com/a/1726321/2425366
void RemoveSpaces(char * source) {
char * i = source, * j = source;
while (*j != 0) {
*i = *j++;
if (*i != ' ') i++;
}
*i = 0;
}
检查这个线程:) http://stackoverflow.com/questions/使用功能5891610/how-to-string-characters-from-a-string – Zerray
'std :: cout'真的很可怕吗?这只是另一个完全相同的名字。 – john
你的问题是不明确的,你想从字符串中删除所有空格,你只是想从字符串的末尾删除它们,也许你想从开始和结束,但不是中间删除它们?您需要清楚地询问您是否需要适当的答案。 – john