

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Parsing a comma-delimited std::string in C++
In this program we will see how to parse comma-delimited string in C++. We will put a string where some texts are present, and they are delimited by comma. After executing this program, it will split those strings into a vector type object.
To split them we are using the getline() function. The basic syntax of this function is like:
getline (input_stream, string, delim)
This function is used to read a string or a line from input stream.
Input: Some strings "ABC,XYZ,Hello,World,25,C++" Output: Separated string ABC XYZ Hello World 25 C++
Algorithm
Step 1: Create stream from given string Step 2: While the stream is not completed Step 2.1: Take item before comma Step 2.2: Add item into a vector Step 3: Return the vector
Example Code
#include<iostream> #include<vector> #include<sstream> using namespace std; main() { string my_str = "ABC,XYZ,Hello,World,25,C++"; vector<string> result; stringstream s_stream(my_str); //create string stream from the string while(s_stream.good()) { string substr; getline(s_stream, substr, ','); //get first string delimited by comma result.push_back(substr); } for(int i = 0; i<result.size(); i++) { //print all splitted strings cout << result.at(i) << endl; } }
Output
ABC XYZ Hello World 25 C++
- Related Questions & Answers
- C# program to convert several strings into a single comma-delimited string
- Replacing numbers on a comma delimited result with MySQL?
- Combining multiple rows into a comma delimited list in MySQL?
- PHP program to split a given comma delimited string into an array of values
- MySQL select distinct rows into a comma delimited list column?
- Remove spaces from std::string in C++
- How to collapse rows into a comma-delimited list with a single MySQL Query?
- How to concatenate a std::string and an int in C++?
- Read whole ASCII file into C++ std::string
- How to convert std::string to LPCSTR in C++?
- How to convert std::string to LPCWSTR in C++?
- Print a Vector in a comma-delimited list, in index order and surrounded by square brackets ([]) in Java
- std::vector::resize() vs. std::vector::reserve() in C++
- Difference between std::vector and std::array in C++
- Remove comma from a string in PHP?
Advertisements