What is the method for splitting strings in C++?

There are various ways in C++ to split a string into substrings. Here are some common methods:

  1. Could you rephrase the following natively in English, please?
  2. read a line of text from standard input
  3. standard string stream
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::string str = "Hello,World,Example,String";
  std::stringstream ss(str);
  std::vector<std::string> tokens;
  std::string token;

  while (std::getline(ss, token, ',')) {
    tokens.push_back(token);
  }

  for (const auto& elem : tokens) {
    std::cout << elem << std::endl;
  }

  return 0;
}
  1. locate
  2. extract or retrieve a portion of a string
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::string str = "Hello,World,Example,String";
  std::vector<std::string> tokens;
  std::string delimiter = ",";
  size_t pos = 0;

  while ((pos = str.find(delimiter)) != std::string::npos) {
    std::string token = str.substr(0, pos);
    tokens.push_back(token);
    str.erase(0, pos + delimiter.length());
  }

  tokens.push_back(str);

  for (const auto& elem : tokens) {
    std::cout << elem << std::endl;
  }

  return 0;
}

These methods can be chosen according to specific situations, and the separator parameter in the code can be adjusted based on different separators.

bannerAds