删除字符串中换行符 c++
How to remove newline characters from a string in C++?
如何从C ++中的字符串中删除换行符?
For example, a string like
例如,像这样的字符串
line 1
line 3
line 4
should be converted to
应该转换为
line 1line 3line 4
方法1:使用`erase()`和`remove()` (Method 1: use `erase()` and `remove()`)
In short, use this code snippet:
简而言之,请使用以下代码段:
input.erase(std::remove(input.begin(), input.end(), '\n'),
input.end());
std::remove()
shifts all elements that are equal to the value \n
by moving the elements in the range to the end and returns the past-the-end iterator for the new range of values that are not \n
.
std::remove()
通过将范围中的元素移到末尾来移动所有等于值\n
的元素,并为非\n
的新值范围返回过去的迭代器。
std::erase()
removes elements from the container in the range specified and updates the size of the vector.
std::erase()
在指定范围内从容器中删除元素,并更新向量的大小。
For the above piece of code, the range of elements removed are all \n
s.
对于上面的代码,删除的元素范围都是\n
s。
A full example program,
完整的示例程序
#include <iostream>
#include <algorithm>
int main ()
{
std::string input{"line 1\n\n\nline 3\nline 4"};
std::cout << "input:\n" << input << "\n";
input.erase(std::remove(input.begin(), input.end(), '\n'), input.end());
std::cout << "After:\n" << input << "\n";
return 0;
}
Execution outputs:
执行输出:
input:
line 1
line 3
line 4
After:
line 1line 3line 4
方法2:使用`regex_replace()` (Method 2: use `regex_replace()`)
Use a regular expression to match consequence \n
s and replace the matched strings with ""
(empty string).
使用正则表达式匹配结果\n
然后将匹配的字符串替换为""
(空字符串)。
#include <iostream>
#include <algorithm>
#include <regex>
int main ()
{
std::string input{"line 1\n\n\nline 3\nline 4"};
std::cout << "input:\n" << input << "\n";
std::regex newlines_re("\n+");
auto result = std::regex_replace(input, newlines_re, "");
std::cout << "After:\n" << result << "\n";
return 0;
}
Execution results:
执行结果:
input:
line 1
line 3
line 4
After:
line 1line 3line 4
翻译自: https://www.systutorials.com/how-to-remove-newline-characters-from-a-string-in-c/
删除字符串中换行符 c++