在 std::string 的末尾插入换行符

Inserting a newline near the end of a std::string

本文关键字:插入 换行符 std string      更新时间:2023-10-16

我正在努力尝试实现一个C++代码解决方案,该解决方案将允许我在std::string末尾插入换行符(即字符串文字'n'(,而不是像大多数实现显示的那样在最后

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

谢谢!

这是一种方法:

std::string test{"abcdef"};
if (!test.empty())
test.insert(test.length() - 1, "n");

这是一个基于迭代器的:

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