string中的find函数

  今天看代码,发现对STL中find函数掌握还是有点少,现在总结一下find函数的用法。

  在非string类型的容器里,可以直接找出所对应的元素。find函数需要几个参数:迭代器、下标志、所要找的元素。

  例如:

   vector<int>  a;

   find(a.begin(),a.end(),1);

   这句话就表示从a的头开始一直到尾,找到第一个值为1的元素,返回的是一个指向该元素的迭代器。

find函数一般在string中使用较广,find函数有一系列的函数,今天简单总结一下:

1.find()

(1)find()函数查找第一次出现的目标字符串。

#include <string>
#include <iostream>
using namespace std;
int main()
{
	string str1("i am a student");
	string str2("student");
	string::size_type pos = str1.find(str2,8);   //在字符串str1中寻找字符串str2

	if (pos == str1.npos)       //对于字符串str1中没有该字符串str2的情况做出处理
	{
		cout << "没有找到str2" << endl;
		return 0;
	}

	cout << "Found str2 at str1: " << pos << endl;    //打印字符串str2在str1中开始的位置
	cout << "Element:" << str2 << endl;                

	return 0;
}

 

若将str1改为“i  am  a  student  student”,那么结果会发生改变吗?

 

我们发现答案和第一次运行的结果是一致的,因此find()只返回第一次出现的目标字符串。

(2)find(string  str,  int  pos)

如果find()函数中除了有被找寻的字符串,还有一位整型数,表示从改位置开始遍历被搜索的字符串,已找到被找寻的字符串。

将上面的代码简单的修改一下

现在从第八位开始遍历str1,有上面的运行结果我们应该知道现在应该找不到str2,运行结果:

2.find_first_of()

find_first_of()表示查找字符串的某个字符最先出现的位置,find_first_of()不是全匹配,即它不是必须要查找的字符串在被查找的字符串中全部出现,而是出现个别字符即可。

我重新举一个例子:

#include <string>
#include <iostream>
using namespace std;
int main() {
	string numerics("0123456789");
	string name("r2d2");
	string::size_type pos = name.find_first_of(numerics);
	if (pos == name.npos)
	{
		return 0;
	}
	cout << "Found numercis at name: " << pos << endl;    
	cout << "Element:" << name[pos] << endl;
}

可以看出,该函数是将被查找的字符串和查找的字符串中第一个重复的字符的下标返回回来。

3.find_last_of()

find_last_of()函数与find_first_of()功能差不多,只不过find_first_of()是从字符串的前面往后面搜索,而find_last_of()是从字符串的后面往前面搜索。

4.rfind()

rfind()函数是反向查找字符串,即找到最后一个与子串匹配的位置

5.find_first_not_of()

find_first_not_of()函数是找到第一个不与子串匹配的位置
 

猜你喜欢

转载自blog.csdn.net/weixin_42736024/article/details/84866216