C++ 从多行字符串中删除新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1488775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Remove new line from multiline string
提问by shergill
Whats the most efficient way of removing a 'newline' from a std::string?
从 std::string 中删除“换行符”的最有效方法是什么?
回答by luke
回答by Greg Hewgill
If the newline is expected to be at the end of the string, then:
如果预计换行符位于字符串的末尾,则:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
If the string can contain many newlines anywhere in the string:
如果字符串可以在字符串的任何位置包含多个换行符:
std::string::size_type i = 0;
while (i < s.length()) {
i = s.find('\n', i);
if (i == std::string:npos) {
break;
}
s.erase(i);
}
回答by coppro
You should use the erase-remove idiom, looking for '\n'. This will work for any standard sequence container; not just string.
您应该使用擦除-删除习语,寻找'\n'. 这适用于任何标准序列容器;不只是string。
回答by edW
Here is one for DOS or Unix new line:
这是 DOS 或 Unix 换行符之一:
void chomp( string &s)
{
int pos;
if((pos=s.find('\n')) != string::npos)
s.erase(pos);
}
回答by mkungla
Another way to do it in the for loop
在 for 循环中执行此操作的另一种方法
void rm_nl(string &s) {
for (int p = s.find("\n"); p != (int) string::npos; p = s.find("\n"))
s.erase(p,1);
}
Usage:
用法:
string data = "\naaa\nbbb\nccc\nddd\n";
rm_nl(data);
cout << data; // data = aaabbbcccddd
回答by mkungla
Use std::algorithms. This question has some suitably reusable suggestions Remove spaces from std::string in C++
使用 std::algorithms。这个问题有一些适当的可重用建议从 C++ 中的 std::string 中删除空格
回答by hrnt
s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
回答by P Shved
The code removes allnewlines from the string str.
该代码从 string 中删除所有换行符str。
O(N) implementation best served without comments on SO and withcomments in production.
而对SO的意见和O(N)的实施提供最好的服务与生产的意见。
unsigned shift=0;
for (unsigned i=0; i<length(str); ++i){
if (str[i] == '\n') {
++shift;
}else{
str[i-shift] = str[i];
}
}
str.resize(str.length() - shift);
回答by Kirill V. Lyadvinsky
std::string some_str = SOME_VAL;
if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' )
some_str.resize( some_str.length()-1 );
or (removes several newlines at the end)
或(最后删除几个换行符)
some_str.resize( some_str.find_last_not_of(L"\n")+1 );
回答by csiz
If its anywhere in the string than you can't do better than O(n).
如果它在字符串中的任何位置都比 O(n) 做得更好。
And the only way is to search for '\n' in the string and erase it.
唯一的方法是在字符串中搜索 '\n' 并删除它。
for(int i=0;i<s.length();i++) if(s[i]=='\n') s.erase(s.begin()+i);
For more newlines than:
对于比以下更多的换行符:
int n=0;
for(int i=0;i<s.length();i++){
if(s[i]=='\n'){
n++;//we increase the number of newlines we have found so far
}else{
s[i-n]=s[i];
}
}
s.resize(s.length()-n);//to delete only once the last n elements witch are now newlines
It erases all the newlines once.
它会擦除所有换行符一次。

