How to Split a C++ String into a Vector of Substrings?
Last Updated :
01 Mar, 2024
In C++, splitting a string into a vector of substrings means we have to split the given string into a substring based on a given delimiter and store each substring in a vector. In this article, we will learn how to split a string into a vector of substrings in C++.
Example:
Input:
str= "Hello, I am Geek from Geeksforgeeks "
Delimiter= ' '
Output:
Hello,
I
am
Geek
from
Geeksforgeeks
Split an std::string into a Vector of Strings in C++
To split a std::string into a std::vector of substrings use the stringstream with a combination of std::string::getline. The below steps shows how to do that:
Approach
- Create an input string stream from the input string using the stringstream.
- Iterate through the stream, using
getline
to extract the substring using the delimiter.
- Add the extracted substring to the vector.
- Print the vector of substrings.
C++ Program to Split a String into Vector of Substrings
The below example demonstrates how we can split a given string into a vector of substrings in C++.
C++
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string> splitString(string& input, char delimiter)
{
istringstream stream(input);
vector<string> tokens;
string token;
while (getline(stream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main()
{
string input = "Hello, I am Geek from Geeksforgeeks" ;
char delimiter = ' ' ;
vector<string> vecOfSubStr
= splitString(input, delimiter);
for ( auto & it : vecOfSubStr) {
cout << it << endl;
}
return 0;
}
|
Output
Hello,
I
am
Geek
from
Geeksforgeeks
Time complexity: O(n), here n is the length of the input string.
Auxilliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...