2
I was looking for a way to implement the . split() C# function in C++ and found the following code in google:
std::vector<std::string> split(const std::string& text, char sep)
{
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos)
{
tokens.push_back(text.substr(start, end - start));
start = end + 1;
}
tokens.push_back(text.substr(start));
return tokens;
}
I put the code in my little project, tested it and saw that it worked, so I left soon to try to understand exactly how the algorithm works. I understood most of the code, but I stuck to the while condition part:
while ((end = text.find(sep, start)) != std::string::npos)
I kind of understood that it checks to see if there’s still the value of char Sep (a ',' e.g. ) in the string, but I couldn’t understand as he does that. Could someone please explain to me in detail how this piece of code works? Thank you very much.
Let me get this straight; if the. find() not finding the character (end = text.find(Sep, start)), it returns npos to the end and then evaluates whether the end is different from npos, right? (end != Std::string::npos)
– Pedro
@Pedro yes, that’s right.
– Vinicius Fernandes
thank you very much, man. I understand perfectly now!
– Pedro