-2

I'm struggling with trying to implement a C++ code solution that will allow me to insert a newline (i.e. a string literal '\n') towards the end of a std::string, and not at the very end as most implementations show.

For example, I want to insert a '\n' just -1 characters before the very end itself. So if the string was 100 characters long (poor analogy I know), then I'd like to insert the string literal at the 99th character in a clean, easily readable manner.

Thanks!

Phobos D'thorga
  • 439
  • 5
  • 17
  • 1
    Perhaps [this `std::string` reference](https://en.cppreference.com/w/cpp/string/basic_string) could be of help? It should at least tell that there's a function ti *insert* characters into a string at an arbitrary (but valid) position. – Some programmer dude Aug 07 '19 at 06:47

1 Answers1

3

Here's one way:

std::string test{"abcdef"};

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

and here's one based on iterators:

if (!test.empty())
   test.insert(std::prev(test.end()), '\n');
lubgr
  • 37,368
  • 3
  • 66
  • 117