Search code examples
c++stdstring

I do not understand this substring behavior . Rather trivial but it boggles my mind


string A = "LOLWUT";

cout << A.substr(0, A.length() - 1) << endl;
cout << A.substr(1, A.length() - 1) << endl;

This code prints:

LOLWU
OLWUT

From my understanding, it should be:

LOLWU
OLWU

Why? What am I missing? It's a simple thing that I came across while at work today, and I can work around it, but I would like to understand it.

My g++ version:

g++ (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders) 13.1.0


Solution

  • The second argument is not the index at which to stop copying, it is how many characters to copy starting at the first argument.

    https://cplusplus.com/reference/string/string/substr/

    string substr (size_t pos = 0, size_t len = npos) const;