C++ string中find,find_first_of和find_last_of的用法

1 str.find(str1)

size_t find (const string& str, size_t pos = 0)

说明:从pos(默认是0,即从头开始查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的起始索引位置;如果没有找到则返回string::npos

str1.find(str2);          //  从串str1中查找时str2,返回str2中首个字符在str1中的地址
str1.find(str2, 5);       //   从str1的第5个字符开始查找str2
str1.find("usage");      //   如果usage在str1中查找到,返回u在str1中的位置
str1.find("o");          //   查找字符o并返回地址
str1.find("of big", 2, 2); //   从str1中的第二个字符开始查找of big的前两个字符

2 str.find_first_of(str1, pos)

/**
*  @brief  Find position of a character of string.
*  @param __str  String containing characters to locate.
*  @param __pos  Index of character to search from (default 0).
*  @return  Index of first occurrence.
*
*  Starting from @a __pos, searches forward for one of the
*  characters of @a __str within this string.  If found,
*  returns the index where it was found.  If not found, returns
*  npos.
*/
size_type
find_first_of(const basic_string& __str, size_type __pos = 0) const
_GLIBCXX_NOEXCEPT
{ return this->find_first_of(__str.data(), __pos, __str.size()); }

2.1 说明

pos位置(默认是0,即从头开始查找)开始查找str1,从前往后,如果找到str1中的任何一个字符,则返回其在str中的索引值;如果没有找到,则返回string::npos

2.2 使用

程序:

// string::find_first_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("Please, replace the vowels in this sentence by asterisks.");
  std::size_t found = str.find_first_of("aeiou");
  while (found!=std::string::npos)
  {
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
  }

  std::cout << str << '\n';

  return 0;
}

输出:

Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.

3 str.find_last_of(str1, pos)

/**
*  @brief  Find last position of a character.
*  @param __c  Character to locate.
*  @param __pos  Index of character to search back from (default end).
*  @return  Index of last occurrence.
*
*  Starting from @a __pos, searches backward for @a __c within
*  this string.  If found, returns the index where it was
*  found.  If not found, returns npos.
*
*  Note: equivalent to rfind(__c, __pos).
*/
size_type
find_last_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT
{ return this->rfind(__c, __pos); }

3.1 说明

npos(默认是字符串最后一个,即从后向前查找)开始查找,如果找到str1中的任何一个字符,则返回其在str中的索引值;如果没有找到则返回string::npos

3.2 使用

程序:

// string::find_last_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>         // std::size_t

void SplitFilename (const std::string& str)
{
  std::cout << "Splitting: " << str << '\n';
  std::size_t found = str.find_last_of("/\\");
  std::cout << " path: " << str.substr(0,found) << '\n';
  std::cout << " file: " << str.substr(found+1) << '\n';
}

int main ()
{
  std::string str1 ("/usr/bin/man");
  std::string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}

输出:

Splitting: /usr/bin/man
path: /usr/bin
file: man
Splitting: c:\\windows\\winhelp.exe
path: c:\\windows
file: winhelp.exe

4 举例

4.1 用例

程序:

#include<iostream>          
using namespace std;        
                            
int main(void)              
{                           
    string s = "一蓑烟雨任平生。";
    int len = s.size();     
    int count = s.size() / string("一").size();
    cout << "len = " << len << ", count = " << count << endl;
    cout << "find:平: pos = " << s.find("平") << endl;
    cout << "find_first_of:平: pos = " << s.find_first_of("平") << endl;
    cout << "find_last_of:平: pos = " << s.find_last_of("平") << endl;
    int pos = s.find("平", 9);                                                                                                                          
    cout << "pos:" << pos << endl;
    cout << "。: pos = " << s.find("。") << endl;
    cout << "。: pos = " << s.find_last_of("。") << endl;
    return 0;               
} 

输出结果:

len = 24, count = 8
find:: pos = 15
find_first_of:: pos = 15
find_last_of:平: pos = 17
pos:15: pos = 21: pos = 23

总结:

C++中一个中文字符(包括汉字和中文符号)在字符串中的长度是3。在一个字符串中查找中文字符的时候最好不要用find_last_of,因为用find_last_of返回的是这个中文字符串的最后一个pos,而不是第一个,极容易出错。

如上述例子如果判断一句话是否是以句号结尾,如果用find_last_of进行查找会得到23而一个句号的长度是3,加起来会大于整个字符串的长度,主要原因还是容易忘记他是子串的最后一个pos,如果用find或者find_first_of,出错概率较低。

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

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;
    }
};
输入:hello
返回:holle

6 参考资料

https://www.cnblogs.com/zh20130424/p/11099932.html

https://blog.csdn.net/weixin_38285131/article/details/83051882

http://www.cplusplus.com/reference/string/string/find/

http://www.cplusplus.com/reference/string/string/find_first_of/

http://www.cplusplus.com/reference/string/string/find_last_of/

  • 10
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值