删除字符串中换行符 c++_如何从C ++中的字符串中删除换行符?

删除字符串中换行符 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 \ns.

对于上面的代码,删除的元素范围都是\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 \ns 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++

  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值