Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide a std::string without copying

Tags:

c++

string

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?

like image 444
Alessandro Power Avatar asked Nov 15 '16 18:11

Alessandro Power


2 Answers

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.

like image 108
SergeyA Avatar answered Nov 06 '22 03:11

SergeyA


I don't know which compiler you are using but at least Microsoft's GSL has string_span which is essentially a string_view.

like image 39
Iikka Olli Avatar answered Nov 06 '22 03:11

Iikka Olli