Home > Article > Backend Development > How Can You Split Strings with Multiple Delimiters in C ?
Splitting Strings with Multiple Delimiters
When tasked with dividing text into meaningful units, developers often encounter the need to separate a string into words. While conventional methods suffice for singular delimiters, what options are available when multiple delimiters are involved?
To address this challenge, a technique employing multiple delimiters for string splitting can be implemented. Let's delve into the solution.
In C , the syntax for parsing a string with a single delimiter using a string stream is as follows:
std::stringstream stringStream(inputString); std::string word; while(std::getline(stringStream, word, delimiter)) { wordVector.push_back(word); }
To accommodate multiple delimiters, we first read the entire line into a buffer. Subsequently, we iterate over the line, identifying positions where any of the specified delimiters appear. By subtracting the previous position from the current delimiter position, we obtain the substring representing the word and add it to the word vector.
For instance, if we choose space, apostrophe, and semi-colon as delimiters, the following code accomplishes the task:
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)); }
The above is the detailed content of How Can You Split Strings with Multiple Delimiters in C ?. For more information, please follow other related articles on the PHP Chinese website!