Vector to comma separated string in C++
In this tutorial, we will learn how to convert a vector to a comma-separated string in C++.
Example:
Vector – {‘P’,’Q’,’R’,’S’}
String – P, Q, R, S
There are mainly 3 methods that are widely used to convert a vector to a string. We will discuss all three methods with the help of code.
1. Using String Stream and iterator
In this method, we will create a stringstream, traverse the vector with the help of the iterator. The elements can be added to the stringstream by dereferencing the iterator.
Syntax
stringstream_name << *iterator << delimiter;
Example:
#include <bits/stdc++.h> #include <sstream> using namespace std; int main() { vector<char> v{'P','Q','R','S'}; stringstream s; // creating stringstream object for (auto it = v.begin(); it != v.end(); it++) { if(it!=v.end()-1) s<< *it << ","; else s<<*it; } cout << s.str() << endl; return 0; }
Output:
P,Q,R,S
2. Using String Stream and index
In this method also we will create the stringstream but traverse the vector through the index and add the elements to stringstream.
Syntax:
stringstream_name << vector_element << delimiter;
Example:
#include <bits/stdc++.h> #include <sstream> using namespace std; int main() { vector<char> v = { 'P','Q','R','S' }; stringstream s; for (int i = 0; i < v.size(); i++) { if(i!=v.size()-1) s<< v[i] << ","; else s<<v[i]; } cout << s.str() << endl; return 0; }
Output: P,Q,R,S
3. Using copy()
In this method, we will create a ostringstream, and using the copy() we will copy the vector through ostream_iterator, vector iterator range, and vector.back().
Syntax:
copy(begin iterator, end iterator-1, ostream iterator <Type> (ostringstream_name, delimiter); ostringstream_name << vector.back();
Example:
#include <bits/stdc++.h> using namespace std; int main() { vector<char> v{'P','Q','R','S'}; ostringstream s; if (!v.empty()) { // using copy() method to copy the elements of the vector to the ostringstream object copy(v.begin(), v.end() - 1,ostream_iterator<char>(s, ",")); s<< v.back(); } cout << s.str() << endl; return 0; }
Output: P,Q,R,S
We can use these methods with any data type of the vector.
Leave a Reply