Open In App

Program to Parse a comma separated string in C++

Given a comma-separated string, the task is to parse this string and separate the words in C++.

Examples: 



Input: "1,2,3,4,5"
Output: 
1
2
3
4
5

Input: "Geeks,for,Geeks"
Output: 
Geeks
for
Geeks

Approach:

Below is the implementation of the above approach:






// C++ program to parse a comma-separated string
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string str = "1,2,3,4,5,6";
    vector<string> v;
 
    stringstream ss(str);
 
    while (ss.good()) {
        string substr;
        getline(ss, substr, ',');
        v.push_back(substr);
    }
 
    for (size_t i = 0; i < v.size(); i++)
        cout << v[i] << endl;
}

Output: 
1
2
3
4
5
6

 

Time Complexity: O(N), as we are using a single loop to iterate over the entire string.
Auxiliary Space: O(N),  as we are storing all the tokens in a vector.

Article Tags :