c++ STL String搜索操作及例子

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";
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_not_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;
        }
       
    
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章