When we use the std::string::find()
function to locate a delimiter within a string, it returns the index (position) of the first character of the delimiter. However, we often want to continue processing the string after the delimiter. This is why we use Start = End + 1
.
Remember that in C++, string indices start at 0
. So, the first character of a string is at index 0
, the second is at index 1
, and so on.
When find()
locates a delimiter like \n
(newline) or ,
(comma), the End
variable will hold the index of that delimiter character. If we want to move to the next part of the string, we need to skip over the delimiter. Adding 1
to End
effectively moves us to the very next character, right after the delimiter.
Let's consider a simple example with a comma-separated string:
#include <iostream>
#include <string>
int main() {
std::string Data{"apple,banana,orange"};
size_t Start{0};
// Find the first comma
size_t End{Data.find(',')};
std::cout << "First part: "
<< Data.substr(Start, End - Start) << "\n";
// Move past the comma
Start = End + 1;
// Find the next comma
End = Data.find(',', Start);
std::cout << "Second part: "
<< Data.substr(Start, End - Start);
}
First part: apple
Second part: banana
In this example:
End
is initially set to the index of the first comma.Data.substr(Start, End - Start)
extracts "apple"Start = End + 1
moves Start
to the position after the comma, which is the first character of "banana".If we didn't add 1, Start would keep pointing to the comma, and we'd get stuck processing the same part of the string repeatedly.
Answers to questions are automatically generated and may not have been reviewed.
std::string
Learn how to read, parse, and use config files in your game using std::string
and SDL_RWops