How to Split a String by a Delimiter in C++?
Last Updated :
14 Feb, 2024
In C++, a string stores a sequence of characters that represents some textual data. The delimiters are used to separate those sequences of characters in a string. This process is called splitting or tokenization. In this article, we will learn how to split a string by a delimiter in C++.
For Example,
Input:
str="geeks,for,geeks"
Output:
String after splitting:
geeks
for
geeks
Split String Using Delimiter in C++
To split a string using a delimiter, we can use std::getline
combined with std::stringstream
to extract all the tokens from the string
separated by a specified delimiter, and keep storing the token in a vector of string.
C++ Program to Split a String by a Delimiter
C++
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string inputString = "geeks,for,geeks" ;
stringstream ss(inputString);
string token;
vector<string> tokens;
char delimiter = ',' ;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
cout << "String after splitting: " << endl;
for ( const auto & part : tokens) {
cout << part << endl;
}
return 0;
}
|
Output
String after splitting:
geeks
for
geeks
Time Complexity: O(n)
Space Complexity: O(n)
Share your thoughts in the comments
Please Login to comment...