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++.
Input: "1,2,3,4,5" Output: 1 2 3 4 5 Input: "Geeks,for,Geeks" Output: Geeks for Geeks
- 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:
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.