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++
// C++ Program to illustrate how to split a string into an // array of substrings #include <iostream> #include <sstream> #include <string> using namespace std; // Function to split a string into tokens based on a // delimiter void splitString(string& input, char delimiter, string arr[], int & index) { // Creating an input string stream from the input string istringstream stream(input); // Temporary string to store each token string token; // Read tokens from the string stream separated by the // delimiter while (getline(stream, token, delimiter)) { // Add the token to the array arr[index++] = token; } } int main() { // Input string string input = "Hello, I am Geek from w3wiki" ; // Delimiter char delimiter = ' ' ; // Array to store the substrings string arrayOfSubStr[100]; // Index to keep track of the number of substrings int index = 0; // Calling the function to split the input string into // an array of substrings splitString(input, delimiter, arrayOfSubStr, index); // Print the array of substrings for ( int i = 0; i < index; i++) { cout << arrayOfSubStr[i] << endl; } return 0; } |
Output
Hello, I am Geek from w3wiki
Time complexity: O(N), here N is the length of the input string.
Auxiliary Space: O(N)
How to Split a String into an Array in C++?
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 w3wiki” Delimiter= ’ ’ Output: Hello, I am Geek from w3wiki
Contact Us