How to split and iterate a string separated by a specific character in C++?

Posted on

How to split and iterate a string separated by a specific character in C++? For example,

"a string   separated by space" by ' '=>
["a", "string", "separated", "by", "space"]

and

"a,string,separated,by,comma" by ',' =>
["a", "string", "separated", "by", "comma"]

C++ standard library’s getline() function can be used to build a function. getline() can accept a delimiter character.

template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline(
  std::basic_istream<CharT,Traits>& input,
  std::basic_string<CharT,Traits,Allocator>& str,
  CharT delim
);

Then the string vector can be iterated using common ways such as range-based for loop.

Here is a C++ function to split the string into a string vector by the delimiter character.

#include <string>
#include <sstream>
#include <vector>

std::vector<std::string> split(const std::string str, char delim)
{
  std::vector<std::string> result;
  std::istringstream ss{str};
  std::string token;
  while (std::getline(ss, token, delim)) {
    if (!token.empty()) {
      result.push_back(token);
    }
  }
  return result;
}

A full C++ function is as follows.

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

std::vector<std::string> split(const std::string str, char delim)
{
  std::vector<std::string> result;
  std::istringstream ss{str};
  std::string token;
  while (std::getline(ss, token, delim)) {
    if (!token.empty()) {
      result.push_back(token);
    }
  }
  return result;
}

int main ()
{
  auto v1 = split(std::string{"a string   separated by space"}, ' ');

  std::cout << "Split v1:" << std::endl;
  for (auto &s : v1) {
    std::cout << s << std::endl;
  }

  auto v2 = split(std::string{"a,string,separated,by,comma"}, ',');

  std::cout << "---------------\nSplit v2:" << std::endl;
  for (auto &s : v2) {
    std::cout << s << std::endl;
  }

  return 0;
}

The execution result is as follows.

$ ./build/main 
Split v1:
a
string
separated
by
space
---------------
Split v2:
a
string
separated
by
comma

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Related Posts