> 文章列表 > C++string类型内置的搜索函数

C++string类型内置的搜索函数

C++string类型内置的搜索函数

string的搜索操作

string类型一共提供了6种不同的搜索函数,每个函数都有4个重载版本。如果搜索成功,每个搜索操作都会返回一个 string::size_type类型的值,表示匹配发生位置的下标。

如果搜索失败,则会返回一个名位string::npos的static成员。标准库将npos定义为一个const string::size_type类型,并初始化为-1。但在string类型里面,将npos定义为一个unsigned类型(unsigned int类型的缩写),此初始值意味着在string类型里,npos等于任何string最大的可能大小。

注意:由于在string里,npos类型是unsigned类型的,所以用int来作为接收string搜索操作的返回值不是一个好选择。

string搜索函数的用法

以下所以的搜索函数,会返回指定字符出现的下标,如果未找到,则会返回string::npos

  • s.find(args): 用于搜索字符串中特定子串第一次出现的索引位置。

    原型:size_ type find (const string& str, size_type pos = 0) const noexcept;
    返回:在 pos 后字符串 str 第一次出现处的位置(注意 str 不能为空)
    重载:
    size_t find( const char* s, size_t pos, size_t n ) const;
    size_t find( const char* s, size_t pos = 0 ) const;
    size_t find( char c, size_t pos = 0 ) const;

  • s.rfind(args): 用于搜索字符串中的最后一次出现的子串的索引位置。

    原型:size_ type rfind (const string& str, size_type pos = 0) const noexcept;
    返回:从 pos 后在字符串 str 的最后一次出现的位置(注意 str 不能为空)
    重载:
    size_t rfind( const char* s, size_t pos, size_t n ) const;
    size_t rfind( const char* s, size_t pos = 0 ) const;
    size_t rfind( char c, size_t pos = 0 ) const;

  • s.find_first_of(args): 用于搜索字符串中第一次出现的指定字符或字符子集,并返回其索引位置。

    原型:size_ type find_first_of (const string& str, size_type pos = 0) const noexcept;
    返回:pos 之后字符串中第一个字符出现时,字符串 str 中也可能出现的那个字符出现的位置
    重载:
    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 c, size_t pos = 0 ) const;

  • s.find_last_of(args): 用于搜索字符串中最后一次出现的指定字符或字符子集,并返回其索引位置。

    原型:size_ type find_last_of (const string& str, size_type pos = 0) const noexcept;
    返回:pos 之前字符串中最后一个字符出现时,字符串 str 中也可能出现的那个字符出现的位置
    重载:
    size_t find_last_of( const char* s, size_t pos, size_t n ) const;
    size_t find_last_of( const char* s, size_t pos = 0 ) const;
    size_t find_last_of( char c, size_t pos = 0 ) const;

  • find_first_not_of()是C++中的一个字符串查找函数,它返回当前字符串在指定字符串中首次不匹配的位置。它遍历字符串,并在发现第一个不属于特定字符集的字符的时候返回该字符的索引位置。如果没有这样的字符,则会返回string::npos值。

  • find_last_not_of()**函数也是一个字符串查找函数,它和find_first_not_of()函数类似,只不过它对字符串进行从后往前查找,以便查找最后一个不属于指定字符集的字符。 如果没有这样的字符,则会返回string::npos值。

学习计划指导