
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- C# program to convert several strings into a single comma-delimited string
- PHP program to split a given comma delimited string into an array of values
- Combining multiple rows into a comma delimited list in MySQL?
- Replacing numbers on a comma delimited result with MySQL?
- MySQL select distinct rows into a comma delimited list column?
- How to collapse rows into a comma-delimited list with a single MySQL Query?
- Print a Vector in a comma-delimited list, in index order and surrounded by square brackets ([]) in Java
- Remove comma from a string in PHP?
- Remove spaces from std::string in C++
- Convert a List of String to a comma separated String in Java
- Convert a Set of String to a comma separated String in Java
- Split String with Comma (,) in Java
- How to concatenate a std::string and an int in C++?
- Recursive string parsing into object - JavaScript
- How to sum a comma separated string (string with numbers) in MySQL?

Advertisements