How to Split Strings

beginner c++11 strings

The C++ strings library does not include many common string functions such as split. To implement split we’ll use the method find_first_of to find the character to split the string on. We’ll then return the split string as a std::vector<std::string> using substring (substr). Here’s an example split function:

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

std::vector<std::string> split(const std::string& s, char c) {
  std::vector<std::string> result;
  size_t begin = 0;
  while (true) {
    size_t end = s.find_first_of(c, begin);
    result.push_back(s.substr(begin, end - begin));

    if (end == std::string::npos) {
      break;
    }
  
    begin = end + 1;
  }
  return result;
}

int main() {
  std::string planets{"Mercury,Venus,Earth,Mars"};
  std::cout << planets << "\n";
  
  std::cout << "--- Split on ',' ---\n";
  std::vector<std::string> v = split(planets, ',');
  for (const auto& s : v) {
    std::cout << s << "\n";
  }

  std::cout << "--- Split on 'u' ---\n";
  v = split(planets, 'u');
  for (const auto& s : v) {
    std::cout << s << "\n";
  }

  std::cout << "--- Split on 'x' ---\n";
  v = split(planets, 'x');
  for (const auto& s : v) {
    std::cout << s << "\n";
  }

  std::cout << "--- Split an empty string ---\n";
  v = split("", ',');
  for (const auto& s : v) {
    std::cout << s << "\n";
  }
}
Mercury,Venus,Earth,Mars
--- Split on ',' ---
Mercury
Venus
Earth
Mars
--- Split on 'u' ---
Merc
ry,Ven
s,Earth,Mars
--- Split on 'x' ---
Mercury,Venus,Earth,Mars
--- Split an empty string ---

For more C++ By Example, click here.