How to Split a String into an Array in C++?
Last Updated :
04 Mar, 2024
In C++, splitting a string into an array of substrings means we have to parse the given string based on a delimiter and store each substring in an array. In this article, we will learn how to split a string into an array of substrings in C++.
Example:
Input:
str= “Hello, I am Geek from geeksforgeeks”
Delimiter= ’ ’
Output:
Hello,
I
am
Geek
from
geeksforgeeks
Splitting a String into an Array in C++
To split a string into an array of substrings in C++, we can use the std::istringstream
class from the <sstream>
library to create an input stream from the string. We can then split the string based on some delimiter using getline() and store them into the array of strings.
Approach
- Create an input string stream from the input string using
std::istringstream
.
- Iterate through the stream, using
std::getline
to extract each substring separated by the delimiter.
- Add the extracted substring to the array.
- Print the array of substrings.
C++ Program for Splitting a String into an Array
The below example demonstrates how we can split a given string into an array of substrings in C++.
C++
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void splitString(string& input, char delimiter,
string arr[], int & index)
{
istringstream stream(input);
string token;
while (getline(stream, token, delimiter)) {
arr[index++] = token;
}
}
int main()
{
string input = "Hello, I am Geek from Geeksforgeeks" ;
char delimiter = ' ' ;
string arrayOfSubStr[100];
int index = 0;
splitString(input, delimiter, arrayOfSubStr, index);
for ( int i = 0; i < index; i++) {
cout << arrayOfSubStr[i] << endl;
}
return 0;
}
|
Output
Hello,
I
am
Geek
from
Geeksforgeeks
Time complexity: O(N), here N is the length of the input string.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...