Open In App

How to Split a String by a Delimiter in C++?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ Program to split a string by a delimiter
  
#include <iostream>
#include <sstream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Input string
    string inputString = "geeks,for,geeks";
  
    // Create a stringstream object with the input string
    stringstream ss(inputString);
  
    // Tokenize the input string by comma delimiter
    string token;
    vector<string> tokens;
    char delimiter = ',';
  
    while (getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
  
    // Output the string after splitting
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads