在C++中,对string的操作中,如果需要在字符串中寻找指定的某个值,如在“dkgjoaidjfajlkbestadsjgoaijdl”这样一个字符串中找一个小字符串“hello”,则可以用到string类提供的find()函数,这个函数在库中进行了多次重载,有几种不同的用法。
1.find (const string& str, size_t pos = 0) ;
根据参数构成可以看出来,这个函数接受一个string对象,pos表示下标,这里采用默认参数的方式,因此可以传也可以不传。
string s = "you are the best one";
string s2 = "are";
size_t pos = s.find(s2); //此处pos得到的值为4,对应“are”的起始‘a’的下标4
调用时不给第二个参数默认从下标0开始查找,找到结果则会返回目标位置的初始下标。
2.find (const char* s, size_t pos = 0);
和上一种形式类似,只是第一个参数接受的是const char *类型,即在调用的时候直接显示的用字符串形式传参。
string s = "you are the best one";
size_t pos = s.find("are"); //效果同上个列子,pos=4
3.find (const char* s, size_t pos, size_t n)
这种形式需要注意,第二个参数下标这里不是默认参数,调用时需要传参,第三个参数表示的是第一个参数对应的字符串中从头算起需要匹配的字符个数,具体用法如下:
string s = "you are the best one";
int n = 3,seat = 0;
size_t pos = s.find("are you",seat,n); //在s中第seat位开始搜索“are you”中前n位
除了find函数之外,如果要在一个string中找寻指定位置的的字符串,或者截取,可以用substr函数实现,代码如下:
string s("abcde");
string a=s.substr(0,3); //获得字符串s中 从下标0开始的长度为3的字符串//默认时的长度为从开始位置到尾
cout<<a<<endl;
输出为
abc
如果下面这种情况:
string a = "abcde";
string b = a.substr(3,5); //下标3开始截取,剩余字符不足5个长度
cout << b << endl;
输出:
de