Parsing a comma-delimited std::string in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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++
raja
Published on 28-Mar-2019 13:24:28
Advertisements