C++ find_first_not_of() 和 find_first_of() 和 find()

find_first_not_of()函数

查找当前string与指定的字符串中任意一个字符都不相符的字符,并返回该字符在字符串中第一次出现的位置。

size_t find_first_not_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_not_of ( const char* str, size_t pos, size_t n ) const;
size_t find_first_not_of ( const char* str, size_t pos = 0 ) const;
size_t find_first_not_of ( char ch, size_t pos = 0 ) const;
  • 在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops
  • 在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从pos开始,最多查找n个字符。如果没找到就返回string::nops
  • 在字符串中查找第一个与ch不匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops

注:string::npos 表示string类中各种成员函数失败时返回的值,其值为-1。

find_first_of()函数

搜索字符串中属于任意一个str、s或c的字符,并返回字符串中第一个出现的位置。

size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char ch, size_t pos = 0 ) const;
  • 在字符串中查找第一个与str中的字符相匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops
  • 在字符串中查找第一个与str中的字符相匹配的字符,返回它的位置。搜索从pos开始,最多查找n个字符。如果没找到就返回string::nops
  • 在字符串中查找第一个与ch不匹配的字符,返回它的位置。搜索从pos开始。如果没找到就返回string::nops

注意:以上这两个方法都是查找当前string与指定的字符串中任意一个字符都不相符的字符的位置地址,而不是返回的是与指定的字符串完全匹配的字符串的首地址,如果若要匹配整个字符串,请使用find()。

应用Demo

#include <iostream>
#include <string>
using namespace std;
void find_first_not_of_test(void)
{
    string str="0123456789abcdef";
    int index01=str.find_first_not_of("013");
    cout << index01 << endl;
    int index02=str.find_first_not_of("0123456789abcdef");
    cout << index02 << endl;
}
void find_first_of_test(void)
{
    string str="0123456789abcdef";
    int index=str.find_first_of("456");
    cout << index << endl;
    int index02=str.find_first_of("zx2");
    cout << index02 << endl;
}
void find_test(void)
{
    string str="0123456789abcdef";
    int index=str.find("abc");
    cout << index << endl;
    int index02=str.find("xyz");
    cout << index02 << endl;
}
int main() {
    std::cout << "find_first_not_of_test" << std::endl;
    find_first_not_of_test();
    std::cout << "find_first_of_test" << std::endl;
    find_first_of_test();
    std::cout << "find_test" << std::endl;
    find_test();
    return 0;
}

运行如下:

find_first_not_of_test
2
-1
find_first_of_test
4
2
find_test
10
-1

发布了87 篇原创文章 · 获赞 28 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/MakerCloud/article/details/88929516
今日推荐