luk*_*uke 108
#include <algorithm>
#include <string>
std::string str;
str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
Run Code Online (Sandbox Code Playgroud)
std :: remove的行为可能不是你所期望的.在这里查看它的解释.
如果预期换行符位于字符串的末尾,则:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
Run Code Online (Sandbox Code Playgroud)
如果字符串可以在字符串中的任何位置包含许多换行符:
std::string::size_type i = 0;
while (i < s.length()) {
i = s.find('\n', i);
if (i == std::string:npos) {
break;
}
s.erase(i);
}
Run Code Online (Sandbox Code Playgroud)
这是 DOS 或 Unix 换行符之一:
void chomp( string &s)
{
int pos;
if((pos=s.find('\n')) != string::npos)
s.erase(pos);
}
Run Code Online (Sandbox Code Playgroud)