How to Split a String by Multiple Delimiters in C++?
In C++, while working with string manipulation we may sometimes need to split a string into substrings based on multiple delimiters. In this article, we will learn how to split a string by multiple delimiters in C++.
For Example,
Input: string inputString= "Hello,World;This|is.w3wiki"; string delimiters = ",;.|"; Output: Hello World This is w3wiki
Split a String into Words by Multiple Delimiters in C++
To split a std::string by multiple delimiters, we can use std::string::find_first_of
to search the delimiters in a string with the combination of std::string::substr
to extract the substrings.
Approach
- Start with startPos = 0 and endPos = 0, run a loop until endPos is not equal to string::npos
- Use
std::string::find_first_of
to find the position of the first occurrence of any delimiter.- If found, use
std::string::substr
to extract the substring between startPos and the delimiter position found byfind_first_of
and add it to result.- If not found, extract the substring from startPos to the end of the string and add it to result also set endPos to string::npos to exit the loop.
- Repeat the process until the end of the string is reached.
C++ Program to Split a String by Multiple Delimiters
The below example demonstrates how we can split a given string by multiple delimiters in C++.
C++
// C++ Program to split the string by miltiple delimiters #include <iostream> #include <string> #include <vector> using namespace std; // Function to split a string by multiple delimiters vector<string> splitStringByDelimiters(string& inputString, string& delimiters) { vector<string> result; // Vector to store the split substrings int startPos = 0; int endPos = 0; // Loop until endPos is not equal to string::npos while ((endPos = inputString.find_first_of(delimiters, startPos)) != string::npos) { if (endPos != startPos) { // Checking if the // substring is non-empty result.push_back(inputString.substr( startPos, endPos - startPos)); } startPos = endPos + 1; // Update startPos to the position // after the delimiter } // Extract the substring from startPos to the end of the // string and add it to result if (startPos != inputString.length()) { result.push_back(inputString.substr(startPos)); } return result; } int main() { // string to be splitted string inputString = "Hello,World;This|is.w3wiki" ; // multiple delimiters string delimiters = ",;.|" ; // calling the function to split the string using // multiple delimiters vector<string> substrings = splitStringByDelimiters(inputString, delimiters); // Displaying the string after splitiing for ( const auto & substring : substrings) { cout << substring << endl; } return 0; } |
Output
Hello World This is w3wiki
Time Complexity: O(n)
Auxiliary Space: O(n) , here m is the number of substrings in the result vector.