c++ string find(), rfind(), find_first_of(),find_last_of()

find(), rfind()

函数原型:

int find(const string& str, int pos = 0) const; //查找str第一次出现位置,从pos开始查找

int find(const char* s, int pos = 0) const; //查找s第一次出现位置,从pos开始查找

int find(const char* s, int pos, int n) const; //从pos位置查找s的前n个字符第一次位置

int find(const char c, int pos = 0) const; //查找字符c第一次出现位置

int rfind(const string& str, int pos = npos) const; //查找str最后一次位置,从pos开始查找

int rfind(const char* s, int pos = npos) const; //查找s最后一次出现位置,从pos开始查找

int rfind(const char* s, int pos, int n) const; //从pos查找s的前n个字符最后一次位置

int rfind(const char c, int pos = 0) const; //查找字符c最后一次出现位置

 

find_first_of(),

  • 用法:str.find_first_of(str1,pos)
  • 说明:从pos位置开始查找str1,从前往后,只要查到str1中的任何一个字符有则返回其在str中的索引值

 

find_last_of()

  • 用法:str.find_last_of(str1,pos)
  • 说明:从pos位置开始查找,从后往前,查到str1中的任何一个字符则返回其str中的索引值

 

例题:leetcode 345题:反转字符串中的元音字母

输入:hello
返回:holle

 

class Solution {
public:
    string reverseVowels(string s) {
        int left=0,right=s.size()-1;
        while(left<right)
        {
            left=s.find_first_of("aeiouAEIOU",left);
            right=s.find_last_of("aeiouAEIOU",right);
            if(left<right)
            {
                swap(s[left++],s[right--]);
            }
        }
        return s;
    }
};

 

posted @ 2020-07-13 15:06  r1-12king  阅读(1106)  评论(0编辑  收藏  举报