Moving Past Delimiters

Why do we use Start = End + 1 to move to the next position after finding a delimiter (like \n or ,)?

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.

Understanding String Indices

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.

Example

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:

  1. End is initially set to the index of the first comma.
  2. Data.substr(Start, End - Start) extracts "apple"
  3. 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.

Parsing Data using std::string

Learn how to read, parse, and use config files in your game using std::string and SDL_RWops

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Trimming Extra Spaces
What if a key in our config file has multiple spaces before or after it, such as " KEY : VALUE"? How can we trim leading/trailing spaces from the key and value?
Config from Network Stream
What changes would be needed to load the config from a different source, like a network stream, instead of a file?
Saving Config Changes
How could we extend the Config class to allow writing the configuration back to a file, effectively saving changes made in-game?
Implementing a Default Config
How could we implement a default configuration that is used if the config file is missing or invalid?
Error Line Numbers
When we encounter an error parsing a file, how can we output an error message that includes where the error occurred - for example, the line number within the file?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant