Search code examples
c++substringsubstr

C++ selecting N characters from string


I have a String. Let it be string a = "abcde";.

And I want to select only a few characters (Let me say from 1 to 3).

In python I would do it like a[1:3]. But C++ doesn't allow me to do that. It only allows for example: a[n], not a[n:x].

Is there a way to select n characters from string in C++?

Or do I need to do it with erase()?


Solution

  • You can use substr():

    std::string a = "abcde";
    std::string b = a.substr(0, 3);
    

    Notice that indexing starts at 0.

    If you want to shorten the string itself, you can indeed use erase():

    a.erase(3); // removes all characters starting at position 3 (fourth character)
                // until the end of the string