string

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值