【问题标题】:Inserting a newline near the end of a std::string [duplicate]在 std::string 末尾附近插入换行符 [重复]
【发布时间】:2019-08-07 06:44:32
【问题描述】:

我正在努力尝试实现一个 C++ 代码解决方案,该解决方案将允许我在 std::string 的末尾插入换行符(即字符串文字 '\n',并且 不是在最后。

例如,我想在最后本身之前插入一个 '\n' 只是 -1 字符。因此,如果字符串长度为 100 个字符(我知道的类比很差),那么我想以一种干净、易于阅读的方式在第 99 个字符处插入字符串文字。

谢谢!

【问题讨论】:

  • 也许this std::string reference 会有所帮助?它至少应该告诉在任意(但有效)位置有一个函数 ti insert 个字符到字符串中。

标签: c++ string insert newline std


【解决方案1】:

这是一种方法:

std::string test{"abcdef"};

if (!test.empty())
   test.insert(test.length() - 1, "\n");

这是一个基于迭代器的:

if (!test.empty())
   test.insert(std::prev(test.end()), '\n');

【讨论】:

  • 非常感谢,没有一个例子这么简单。
猜你喜欢
  • 2021-07-21
  • 2012-11-06
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
相关资源
最近更新 更多