C/C++: string的trim()、split()函数实现

其他语言的lib中,对于string类都有丰富的操作函数,而C++中却不提供一些特殊的函数功能。通过现有的一些函数也可以在c++中实现trim( )、split()等功能。

trim函数

trim( )的作用:去掉字符串首尾的空格。
可以借助 string类中的find_first_not_of( )、find_last_not_of( )函数进行构造

	string trim(const string& str) {
		string::size_type pos = str.find_first_not_of(' ');
		if (pos == string::npos) {  //若找不到空格
			return str;
		}
		string::size_type pos2 = str.find_last_not_of(' ');
		if (pos2 != string::npos)
			return str.substr(pos, pos2 - pos + 1); //子串:第一个非空格作为起始位置
			                                        // 字符个数:pos2-pos+1
		return str.substr(pos);
	}

split函数

split函数功能:从字符串中按照特定的分隔符进行分割,分割的结果保存到std::vector中。
例:按照分隔符“ ,”进行分割split

int split(const string& str, vector<string>& rect_, string sep = ","){
		if (str.empty())  return 0;
		
		string tmp;
		string::size_type pos_begin = str.find_first_not_of(sep); //第一个非分隔符的位置
		string::size_type comma_pos = 0;

		while (pos_begin != string::npos) {
			comma_pos = str.find(sep, pos_begin); //从下表pos_begin处开始查找字符“,”,返回其下标
			if (comma_pos != string::npos) { //comma_pos :下一个分隔符的位置
				tmp = str.substr(pos_begin, comma_pos - pos_begin);
				pos_begin = comma_pos + sep.length();
			}
			else {
				tmp = str.substr(pos_begin);
				pos_begin = comma_pos;
			}

			if (!tmp.empty()) {
				rect_.push_back(tmp);
				tmp.clear;
			}
		}
		return 0;
	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值