C++ String Split: Implementation Guide
There is no built-in string split function in C++, but you can create a custom split function to parse strings. Here is a simple example code:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string str = "Hello,World,How,Are,You";
std::vector<std::string> tokens = split(str, ',');
for (const std::string& token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
In the code example above, the split function takes a string and a separator as parameters, divides the string by the separator, and returns a string vector that stores the split results.
First, convert the input string str to a stream object ss using std::stringstream. Next, use the std::getline function to read tokens line by line from ss and add them to the tokens vector.
Finally, in the main function, pass the string “Hello,World,How,Are,You” to the split function with delimiter ‘,’. Then, iterate through the tokens vector in a loop to print out each split result.
The output of running the above code will be:
Hello
World
How
Are
You