C++ string in stl

substr

In stl, we can directly use function substr() to get a substring from a string.

s.substring(<head>, <length>);
s.substring(1, 2);

1 is the starting index for the substring, 2 is the length for the substring, which is unique from other programming languages!

split

stl does not provide built-in function for split. So typically, using two pointers and substr to realize a split function.

vector<string> split(string &s, char ch){
	vector<str> ans;
	for(int i = 0; i < s.size(); i++){
		if(s[i] == 'ch') continue;
		int j = i + 1;
		while(j < s.size() && s[j] != ' ') j++;
		ans.push_back(s.substr(i, j-i));
	}
	return ans;
}

find

find(<first>, <end>, <value>);
find_if(<first>, <end>, [bool] <pred>);

返回区间[first,end)中第一个值等于value的元素位置;若未找到,返回end。函数返回的是迭代器或指针,即位置信息。

参考代码main(),查找findvalue的值

二、std::find_if()

用法:find_if(first, end, bool pred);

返回区间[first,end)中使一元判断式pred为true的第一个元素位置;若未找到,返回end。

参考代码main(),test_find_if();查找第一个被5整除的数,pred写成bool函数

三、std::find_first_of()

用法:find_first_of(first1, end1, first2, end2);

返回第一个区间迭代器位置,满足第一个区间[first1,end1)中的元素第一次出现在第二个区间[first2,end2)中。

通俗就是说顺序从第一个区间[first1,end1)中取一个元素,在第二个区间中找有没有相同的元素,如果有就返回第一个区间中元素位置;未找到则继续

用第一个区间的下一个元素在第二个区间找。

因此只要保证两个区间内的元素可以==即可,不用管装元素的容器形式。下面的例子我第一个区间用的vector、而第二个区间是list也是可以的。

参考代码main(),test_find_first_of();查找vector中第一次出现在list的元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值