How to Split a String by Multiple Delimiters in C++?
Last Updated :
22 Feb, 2024
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.GeeksForGeeks";
string delimiters = ",;.|";
Output:
Hello
World
This
is
GeeksForGeeks
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 by find_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++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> splitStringByDelimiters(string& inputString,
string& delimiters)
{
vector<string>
result;
int startPos = 0;
int endPos = 0;
while ((endPos = inputString.find_first_of(delimiters,
startPos))
!= string::npos) {
if (endPos != startPos) {
result.push_back(inputString.substr(
startPos, endPos - startPos));
}
startPos
= endPos + 1;
}
if (startPos != inputString.length()) {
result.push_back(inputString.substr(startPos));
}
return result;
}
int main()
{
string inputString
= "Hello,World;This|is.GeeksForGeeks" ;
string delimiters = ",;.|" ;
vector<string> substrings
= splitStringByDelimiters(inputString, delimiters);
for ( const auto & substring : substrings) {
cout << substring << endl;
}
return 0;
}
|
Output
Hello
World
This
is
GeeksForGeeks
Time Complexity: O(n)
Auxiliary Space: O(n) , here m is the number of substrings in the result vector.
Share your thoughts in the comments
Please Login to comment...