Splitting Strings with Multiple Delimiters
When working with text, it's often necessary to split a string into individual words or tokens. In cases where a single delimiter is insufficient, here's how to utilize multiple delimiters to achieve this task.
Assuming one of the delimiters is the newline character, the following code snippet demonstrates how to read text from a stringstream, split it into lines, and further subdivide each line based on designated delimiters.
std::stringstream stringStream(inputString); std::string line; while(std::getline(stringStream, line)) { std::size_t prev = 0, pos; while ((pos = line.find_first_of(" ';", prev)) != std::string::npos) { if (pos > prev) wordVector.push_back(line.substr(prev, pos-prev)); prev = pos+1; } if (prev < line.length()) wordVector.push_back(line.substr(prev, std::string::npos)); }
In this code, the line string is read and subsequently processed. The find_first_of function is employed to search for the first occurrence of any character in the specified delimiter string (" ';" in this case). Words are extracted between delimiters, and those at the beginning or end of the line are also captured. The tokens are then added to the wordVector.
The above is the detailed content of How to Split Strings with Multiple Delimiters in C ?. For more information, please follow other related articles on the PHP Chinese website!