C++ String Split Purpose Explained
The purpose of the string split function in C++ is to separate a string into multiple substrings based on a specified delimiter, and store these substrings in a container (such as a vector or array) for retrieval.
Typically, we need to split a string by spaces, commas, or other specific characters, and then use the resulting substrings for further processing and analysis. The String split function offers a convenient way to achieve this functionality without manually writing complex string processing algorithms.
Here is an example code using the string split function:
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string str = "Hello,World,!";
std::vector<std::string> result = split(str, ',');
for (const auto& token : result) {
std::cout << token << std::endl;
}
return 0;
}
The code above splits the string “Hello,World,!” by commas, stores the substrings in a vector, and then outputs each substring one by one. The output is:
Hello
World
!
It is possible to use the string split function to easily divide a string into multiple substrings for further processing and analysis.