Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Program to Parse a comma separated string in C++

  • Last Updated : 24 Oct, 2020

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




 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Approach:
 

  • Get the string in stream – stringstream
  • Create a string vector to store the parsed words
  • Now till there is a string in stringstream, checked by good() method,
    • Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() method
    • This will give the word in the substring
    • Now store this word in the vector
    • This word is now removed from the stream and stored in the vector

Below is the implementation of the above approach:
 

CPP




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




 

My Personal Notes arrow_drop_up
Recommended Articles
Page :