Given an input string which is comma-separated instead of space, the task is to parse this input string in C++.
First, let us understand what difference does it create if the input string is comma-separated.
Taking input a whitespace-separated string
Taking input a whitespace-separated string in C++ is very easy. The program to do so is:
1 2 3 4 5 6
1 2 3 4 5 6
Why can’t we use the above code for comma-separated input string?
The above code works fine for a whitespace-separated input string, but for a comma-separated input string, it won’t work as expected, because the program will take complete input as a single word in the string.
1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 6
How to input a comma separated string?
Now inorder to input a comma separated string, following approach can be used:
- Get the string to be taken as input in stringstream
- Take each character of the string one by one from the stream
- Check if this character is a comma (‘, ‘).
- If yes, then ignore that character.
- Else, Insert this character in the vector which stores the words
Below is the implementation of the above approach:
11 21 31 41 51 61
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.
- Program to Parse a comma separated string in C++
- Comma in C and C++
- Comma operator should be used carefully
- Result of comma operator as l-value in C and C++
- How can we use Comma operator in place of curly braces?
- Print all the duplicates in the input string
- Maximum occurring character in an input string | Set-2
- Program to check if input is an integer or a string
- Return maximum occurring character in an input string
- Generate two output strings depending upon occurrence of character in input string.
- Generate two output strings depending upon occurrence of character in input string in Python
- Input Iterators in C++
- Clearing The Input Buffer In C/C++
- Basic Input / Output in C++
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- String slicing in Python to check if a string can become empty by recursive deletion
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Find the longest sub-string which is prefix, suffix and also present inside the string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.