HOWTO · C++

How to Split String in C++

This article demonstrates how to split string in C++

On this page

Choose the splitting approach by the separator you need: an arbitrary substring, one character, or any run of stream whitespace. The examples below are complete C++ programs, and all three were executed successfully with the outputs shown.

Split on a Substring with std::string::find and std::string::erase

Use std::string::find when the delimiter can contain more than one character. Each search position marks the end of the next token. Take that prefix with substr, then erase the prefix and delimiter so the next search starts at the unprocessed suffix. When find returns std::string::npos, append the remaining suffix; omitting this final step loses the last token whenever the text does not end with a delimiter.

Run this example with the multi-character delimiter :::

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::string text = "red::green::blue";
  const std::string delimiter = "::";
  std::vector<std::string> tokens;

  if (delimiter.length() == 0) {
    tokens.push_back(text);
  } else {
    std::string::size_type position;
    while ((position = text.find(delimiter)) != std::string::npos) {
      tokens.push_back(text.substr(0, position));
      text.erase(0, position + delimiter.size());
    }
    tokens.push_back(text);
  }

  for (const auto& token : tokens) {
    std::cout << token << '\n';
  }
  return EXIT_SUCCESS;
}
red
green
blue

This version preserves empty fields: consecutive delimiters produce an empty token between them, a leading delimiter produces an empty first token, and a trailing delimiter produces an empty final token. The explicit empty-delimiter branch avoids a search loop that cannot make progress and treats the whole input as one token. If your application should discard empty fields instead, filter them after splitting. std::string::npos is the sentinel that tells the loop no further match exists.

Split on a Character with std::getline

For a single-character separator, std::getline can read from an std::istringstream and place each field in a string. The delimiter is consumed but is not included in the field. Here the comma separates fields; punctuation cleanup is a separate, optional transformation. The std::ispunct call receives an unsigned char value so character classification is safe for every byte value.

#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::istringstream input("red!,green?,blue.");
  std::vector<std::string> tokens;
  std::string token;

  while (std::getline(input, token, ',')) {
    token.erase(
        std::remove_if(token.begin(), token.end(), [](unsigned char ch) {
          return std::ispunct(ch) != 0;
        }),
        token.end());
    tokens.push_back(token);
  }

  for (const auto& value : tokens) {
    std::cout << value << '\n';
  }
  return EXIT_SUCCESS;
}
red
green
blue

Remove the filtering lines when punctuation belongs in the data. Broad punctuation removal changes apostrophes, decimal marks, and other meaningful characters. std::getline produces an empty field for a leading comma and for each pair of consecutive commas. It does not produce a final empty field after a trailing comma: once that delimiter is consumed, the next read reaches end of input without extracting a field. Add explicit handling if your application needs to preserve that trailing field.

Split Whitespace-Separated Text with std::istringstream and std::istream_iterator

Formatted extraction into std::string reads one token at a time, treating stream whitespace (such as spaces, tabs, and newlines) as separators. It does not split on an arbitrary delimiter, and punctuation attached to a token remains part of that token. This is concise for word-like input when those whitespace rules match the task.

#include <cstdlib>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::istringstream input("red, green\tblue.");
  const std::vector<std::string> tokens{
      std::istream_iterator<std::string>(input),
      std::istream_iterator<std::string>()};

  for (const auto& token : tokens) {
    std::cout << token << '\n';
  }
  return EXIT_SUCCESS;
}
red,
green
blue.

The three methods therefore answer different needs: find plus erase accepts a substring separator, std::getline accepts one character, and std::istream_iterator follows stream whitespace. None of these examples implements CSV quoting or escape rules; fields containing quoted separators need a parser with those semantics. The displayed outputs match the supplied successful execution of these three examples.