Open In App

How to Split a String into an Array in C++?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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 Geeksforgeeks";
  
    // 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
Geeksforgeeks

Time complexity: O(N), here N is the length of the input string.
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads