6个不同的搜索函数
- 查找s中args第一次出现的位置:
s.find(args)
- 在s中找args中任意一个字符第一次出现的位置:
s.find_first_of(args)
- 在s中查找第一个不在args中的字符:
s.find_first_not_of(args)
逆向搜索:
- 查找s中args最后一次出现的位置:
s.rfind(args)
- 在s中找args中任意一个字符最后一次出现的位置:
s.find_last_of(args)
- 在s中查找最后一个不在args中的字符:
s.find_last_not_of(args)
搜索成功,返回指定字符出现的下标。
失败没找到,则返回npos。
npos为一个名为string::npos的static成员,标准库将npos定义为一个const string::size_type类型,并初始化为-1。
搜索以及其他的string操作是大小写敏感的。
args可以是什么呢:
- c, pos : 从s中位置pos开始查找字符c。pos默认为0
- s2,pos : 从s中位置pos开始查找字符串s2。pos默认为0
- cp,pos : 从s中位置pos开始查找指针cp指向的以空字符结尾的c风格字符串。pos默认0
- cp,pos,n:从s中位置pos开始查找指针cp指向的数组的前n个字符
举例:
1、找字符串中第一个不是空格的字符的索引
string s=" abc";
if(index!=s.npos){//index==s.npos 表示没找到
int index= s.find_first_not_of(' ');//2
}
2、从字符串中索引5的位置开始,找第一个是’+'的字符
string s="abcde+456";
int index= s.find_first_not_of('+', 5);//5
3、找"Chen"第一次在字符串中出现的位置
string s="cbcdChensss";
int index= s.find("Chen");//4
int index2= s.find("chen");//npos
4、找字符串s中第一个是数字的下标
string s="a2yy88";
string numbers="0123456789";
s.find_first_of(numbers);//1
5、找字符串s中第一个不是数字的下标
```cpp
string s="2345p8";
string numbers="0123456789";
s.find_first_not_of(numbers);//4
6、找字符串中最后一个是’#'的字符
string s="abcde#";
int index= s.find_last_of('#');//
应用
把字符串转换成整数:
class Solution {
public:
int StrToInt(string str) {
int m=str.length();
//处理字符串为空
if(m==0) return 0;
int result=0,flag=1;
//处理空格
int index=str.find_first_not_of(' ');
//int index=0;
//while(str[index]==' ' && index< m)
// ++index;
//处理y以"+""-"号开头的整数
if(str[index]=='+' || str[index]=='-')
flag = str[index++]=='-'? -1 : 1;
//处理了溢出和非数字字符
for(;index<m;index++)
{
if(str[index]>='0' && str[index]<='9')
{
result = result*10+(str[index]-'0');
if(result*flag > INT_MAX)
return INT_MAX;
if(result*flag < INT_MIN)
return INT_MIN;
}
else
{
result = 0;
break;
}
}
return result*flag;
}
};