Use stringstream
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
template<class T>
void printInfo(T& s){
for(auto itr=s.begin(); itr!=s.end(); ++itr){
cout << *itr << ' ';
}
cout << endl;
}
int main(){
vector<string> s;
string temp="";
string text = "How,are,you";
istringstream istr(text);
while(!istr.eof()){
getline(istr, temp, ',');
s.push_back(temp);
}
cout << "Size: " << s.size() << endl;
printInfo(s);
return 0;
}
Trim string
void trim1(string& s){
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ")+1, s.size());
}
void trim2(string& s){
auto f = [](unsigned char const c) { return std::isspace(c); };
s.erase(remove_if(s.begin(), s.end(), f), s.end());
}
int main(){
string s = " Hello ";
cout << "Size before trim: " << s.size() << endl;
trim2(s);
cout << "Size after trim: " << s.size() << endl;
printInfo(s);
return 0;
}
trim2 use algorithm remove_if in stl
template <class ForwardIterator, class UnaryPredicate>
ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
UnaryPredicate pred)
{
ForwardIterator result = first;
while (first!=last) {
if (!pred(*first)) {
*result = std::move(*first);
++result;
}
++first;
}
return result;
}
remove_if transforms the range
[first,last)
into a range with all the elements for which
pred returns
true
removed, and returns an iterator to the new end of that range. therefore, trim2 further uses erase delete characters after the new end.