Alessandro Power Alessandro Power - 19 days ago 5
C++ Question

Divide a std::string without copying

Is it possible to divide a

std::string
into two or more substrings without copying, much like we can use a move constructor to create a new
std::string
without copying?

Answer

You can not do this with std::string. But, you can do this with std::string_view from C++17.

Example:

std::string str = "TheBigStr";
std::string_view p1 = std::string_view(str.data() + 3, 3);

String view is not copying the data, so str should not be modified while the view is used.

Comments