C++ equivalent of Python String Slice?

前端 未结 6 1235
灰色年华
灰色年华 2021-01-01 13:30

In python I was able to slice part of a string; in other words just print the characters after a certain position. Is there an equivalent to this in C++?

Python Code

6条回答
  •  鱼传尺愫
    2021-01-01 13:56

    std::string text = "Apple Pear Orange";
    std::cout << std::string(text.begin() + 6, text.end()) << std::endl;  // No range checking at all.
    std::cout << text.substr(6) << std::endl; // Throws an exception if string isn't long enough.
    

    Note that unlike python, the first doesn't do range checking: Your input string needs to be long enough. Depending on your end-use for the slice there may be other alternatives as well (such as using an iterator range directly instead of making a copy like I do here).

提交回复
热议问题