C++字符串string-tirm

2017-08-10 11:24:40 805 次浏览

字符串两端去除字符。支持多种字符trim
string trim(const string & str,const string chs = "\r\n\t ");

string trim(const string & str,const string chs){
	if ( str.empty() ) {
		return str;
	}
	string tmp=str;
  	for ( string::const_iterator it = chs.begin() ; 
			it < chs.end(); it++ ){
		string::size_type first_pos = tmp.find_first_not_of( * it);	
		if ( first_pos == string::npos ) {
				return "";
		}
		
		string::size_type last_post = tmp.find_last_not_of( * it);

		if (last_post != string::npos ){
			tmp = tmp.substr(first_pos,last_post - first_pos + 1);
		}

		tmp = tmp.substr(first_pos);
	}
	return str;
}

评论