Parsing Data using std::string

Moving Past Delimiters

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 79 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved