How to use getline() and stringstream In C++
It works for single-character delimiters.
C++
// C++ Program for Conversion // String To Vector using Delimiter // Using getline() and stringstream #include <bits/stdc++.h> using namespace std; vector<string> split(string str, char delimiter) { // Using str in a string stream stringstream ss(str); vector<string> res; string token; while (getline(ss, token, delimiter)) { res.push_back(token); } return res; } int main() { // Delimiter is " " string s = "w3wiki is a computer science portal" ; vector<string> res = split(s, ' ' ); for ( int i = 0; i < res.size(); i++) { cout << res[i] << endl; } // Delimiter is * s = "w3wiki*is*a*computer*science*portal" ; res = split(s, '*' ); for ( int i = 0; i < res.size(); i++) { cout << res[i] << endl; } return 0; } |
w3wiki is a computer science portal w3wiki is a computer science portal
C++ String to Vector Using Delimiter
Delimiters are used as separators between the characters or words in a string so that different results can get separated by the delimiter. In this article let us see the different ways in which a string with delimiters can be converted to a vector of words after getting separated by delimiters.
Example:
string x=”A B C”;
string y=”A*B*C”;
// Separate x into [‘A’,’B’,’C’] with delimiter ‘ ‘
// Separate y into [‘A’,’B’,’C’] with delimiter ‘*’
Methods that can be used to perform this operation are :
- Using find() function
- Using strtok() function
- Using getline() and stringstream
- Using find_first_not_of() with find() function
- Using regex_token_iterator