Luk*_*rry 7 c++ removing-whitespace
我正在尝试编写一些用下划线替换字符串中所有空格的东西.
到目前为止我有什么.
string space2underscore(string text)
{
for(int i = 0; i < text.length(); i++)
{
if(text[i] == ' ')
text[i] = '_';
}
return text;
}
Run Code Online (Sandbox Code Playgroud)
如果我做的话,大多数情况下这都会有用.
string word = "hello stackoverflow";
word = space2underscore(word);
cout << word;
Run Code Online (Sandbox Code Playgroud)
这将输出"hello_stackoverflow",这正是我想要的.
但是,如果我要做的事情
string word;
cin >> word;
word = space2underscore(word);
cout << word;
Run Code Online (Sandbox Code Playgroud)
我会得到第一个字,"你好".
有人知道解决这个问题吗?
Bla*_*ace 17
你已经getline修复了你的问题,但我只想说标准库包含许多有用的功能.而不是手动循环,你可以做:
std::string space2underscore(std::string text)
{
std::replace(text.begin(), text.end(), ' ', '_');
return text;
}
Run Code Online (Sandbox Code Playgroud)
这很有效,它很快,它实际上表达了你正在做的事情.
Eva*_*ran 14
问题是cin >> word只会在第一个单词中读到.如果你想一次整体操作,你应该使用std::getline.
例如:
std::string s;
std::getline(std::cin, s);
s = space2underscore(s);
std::cout << s << std::endl;
Run Code Online (Sandbox Code Playgroud)
此外,您可能想要检查您实际上是否能够读取一行.你可以这样做:
std::string s;
if(std::getline(std::cin, s)) {
s = space2underscore(s);
std::cout << s << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
最后,作为旁注,您可能会以更清洁的方式编写您的函数.就个人而言,我会这样写:
std::string space2underscore(std::string text) {
for(std::string::iterator it = text.begin(); it != text.end(); ++it) {
if(*it == ' ') {
*it = '_';
}
}
return text;
}
Run Code Online (Sandbox Code Playgroud)
或奖励积分,使用std::transform!
编辑:
如果你碰巧幸运能够使用c ++ 0x功能(我知道这是一个很大的if)你可以使用lambdas std::transform,这会产生一些非常简单的代码:
std::string s = "hello stackoverflow";
std::transform(s.begin(), s.end(), s.begin(), [](char ch) {
return ch == ' ' ? '_' : ch;
});
std::cout << s << std::endl;
Run Code Online (Sandbox Code Playgroud)
问题是与你的理解std::cin从iostream库:使用>>上有一个流运算符std::string的右手边参数只是(用空格分隔),需要一个词在同一时间.
你想要的是std::getline()用来获取你的字符串.