zoukankan      html  css  js  c++  java
  • C++ string的find类函数的使用

    什么是npos:

    std::basic_string<CharT,Traits,Allocator>::npos
    static const size_type npos = -1;

    这是特殊值,等于 size_type 类型可表示的最大值。准确含义依赖于语境,但通常,期待 string 下标的函数以之为字符串尾指示器,返回 string 下标的函数以之为错误指示器。

    注意

    虽然定义使用 -1 ,由于有符号到无符号隐式转换,且 size_type 是无符号整数类型, npos 的值是其所能保有的最大正值。这是指定任何无符号类型的最大值的可移植方式。

    1.find

    size_type find( const basic_string& str, size_type pos = 0 ) const;

    可见需要两个参数,一个是想要找到的string str子串,已经指明从那个位置pos开始找,返回类型为string::size_type

    寻找首个等于给定字符序列的子串。搜索始于 pos ,即找到的子串必须不始于 pos 之前的位置。

    当然,也可以用来寻找一个字符

    正式而言,若下列全部为 true ,则说在位置 xpos 找到子串 str :

    • xpos >= pos
    • xpos + str.size() <= size()
    • 对于 str 中所有位置 n , Traits::eq(at(xpos+n), str.at(n))

    特别是,这隐含

    • 仅若 pos <= size() - str.size() 才能找到子串
    •  pos 找到空子串,若且唯若 pos <= size()
    • 对于非空子串,若 pos >= size() ,则函数始终返回 npos 。

    参数

    str - 要搜索的 string
    pos - 开始搜索的位置
    count - 要搜索的子串长度
    s - 指向要搜索的字符串的指针
    ch - 要搜索的字符
    t - 要搜索的对象(可转换为 std::basic_string_view )

    返回值

    找到的子串的首字符位置,或若找不到这种子串则为 npos 。

    例子:

    #include <string>
    #include <iostream>
    
    void print(std::string::size_type n, std::string const &s){
        if(n == std::string::npos){
            std::cout << "not found
    ";
        }else{
            std::cout << "found: " << s.substr(n) << '
    ';
        }
    }
    
    int main(){
        std::string::size_type n;
        std::string const s = "This is a string";
    
        n = s.find("is");
        print(n,s);
    
        n = s.find("is", 5);
        print(n,s);
    
        n = s.find('a');
        print(n,s);
    
        n = s.find('q');
        print(n,s);
    }

    返回:

    found: is is a string
    found: is a string
    found: a string
    not found

    2.rfind

    size_type rfind( const basic_string& str, size_type pos = npos ) const noexcept;
    size_type rfind( CharT ch, size_type pos = npos ) const noexcept;

    寻找等于给定字符序列的最后子串。搜索始于 pos ,即找到的子串必须不始于 pos 后的位置。若将 npos 或任何不小于 size()-1 的值作为 pos 传递,则在整个字符串中搜索。

    参数

    str - 要搜索的 string
    pos - 开始搜索的位置
    count - 要搜索的子串长度
    s - 指向要搜索的字符串的指针
    ch - 要搜索的字符
    t - 要搜索的对象(可转换为 std::basic_string_view )

    返回值

    找到的子串的首字符位置,或若找不到这种子串则为 npos 。注意这是从字符串开始,而非末尾的偏移。

    若搜索任何空字符串( str.size() 、 count 或 Traits::length(s) 为零),则返回 pos (立即找到空字符串),除非 pos > size() (包括 pos == npos 的情况),该情况下返回 size() 。

    否则,若 size() 为零,则始终返回 npos 。

    这个函数的返回值还是从左边开始数的,只是寻找的时候从字符串的末尾开始找

    例子:

    #include <string>
    #include <iostream>
    
    void print(std::string::size_type n, std::string const &s){
        if(n == std::string::npos){
            std::cout << "not found
    ";
        }else{
            std::cout << "found: "" << s.substr(n) << "" at " << n << '
    ';
        }
    }
    
    int main(){
        std::string::size_type n;
        std::string const s = "This is a string";
    
        n = s.rfind("is");// 从字符串尾反向搜索
        print(n,s);
    
        n = s.rfind("is", 4);// 从位置 4 反向搜索,s所以找到的是This的is
        print(n,s);
    
        n = s.rfind('a');
        print(n,s);
    
        n = s.rfind('q');
        print(n,s);
    }

    返回:

    found: "is a string" at 5
    found: "is is a string" at 2
    found: "a string" at 8
    not found

    3.find_first_of

    constexpr size_type find_first_of( const basic_string& str, size_type pos = 0 ) const noexcept;
    size_type find_first_of( CharT ch, size_type pos = 0 ) const noexcept;

    也是可用于查看字符和字符串,不同在于它会寻找str某个字符出现最早的位置,不一定要全部str

    寻找等于给定字符序列中字符之一的首个字符。搜索只考虑区间 [pos, size()) 。若区间中不存在字符,则返回 npos 。

    参数

    str - 鉴别要搜索的字符的 string
    pos - 搜索开始的位置
    count - 鉴别要搜索的字符的字符串长度
    s - 指向鉴别要搜索的字符的字符串的指针
    ch - 鉴别要搜索的字符的字符
    t - 鉴别要搜索的字符的对象(可转换为 std::basic_string_view )

    返回值

    找到的字符的位置,或若找不到这种字符则为 npos 。

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        std::string str = std::string("Hello world!");
    
        //用来搜索的字符和字符串
        std::string search_str = std::string("o");
        const char* search_cstr = "Good Bye!";
        std::cout << str.find_first_of(search_str) << '
    '; //找到第一个出现o的位置,即Hello的o
        std::cout << str.find_first_of(search_str, 5) << '
    '; //找到从位置5开始第一个出现o的位置,即World的o
        std::cout << str.find_first_of(search_cstr) << '
    '; //寻找字符串中与str有重叠的字符的第一个位置
        std::cout << str.find_first_of(search_cstr, 5, 4) << '
    '; ////寻找字符串search_cstr[0:4]中与str从位置5开始有重叠的字符的第一个位置
        std::cout << str.find_first_of('x') << '
    '; //不存在,则返回std::string::npos
    }

    返回:

    4
    7
    1
    7
    18446744073709551615

    4.find_first_not_of

    寻找不等于给定字符序列中任何字符的首个字符。搜索只考虑区间 [pos, size()) 。若区间中不存在字符,则将返回 npos

    参数

    str - 鉴别要搜索的字符的 string
    pos - 搜索开始的位置
    count - 鉴别要搜索的字符的字符串长度
    s - 指向鉴别要搜索的字符的字符串的指针
    ch - 鉴别要搜索的字符的字符
    t - 鉴别要搜索的字符的对象(可转换为 std::basic_string_view )

    返回值

    找到的字符的位置,或若找不到这种字符则为 npos 。

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        std::string to_search = "Some data with %MACROS to substitute";
        std::cout << "Before: " << to_search << '
    ';
    
        auto pos = std::string::npos;
        while((pos = to_search.find('%')) != std::string::npos){
            // 宏名中容许大写字母、小写字母和数字,会找到空格的位置
            const auto after = to_search.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", pos + 1);
            // 现在 to_search[pos] == '%' 而 to_search[after] == ' ' (在 'S' 后)
            if(after != std::string::npos){
                to_search.replace(pos, after-pos, "some very nice macros");
            }
        }
        std::cout << "After: " << to_search << '
    ';
    }

    返回:

    Before: Some data with %MACROS to substitute
    After: Some data with some very nice macros to substitute

    5.find_last_of

    寻找等于给定字符序列中字符之一的最后字符。不指定准确的搜索算法。搜索只考虑区间 [0, pos] 。若区间中不存在这种字符,则返回 npos 。

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        const std::string path = "/root/config";
        auto const pos = path.find_last_of('/');
        const auto leaf = path.substr(pos+1);
        std::cout << leaf << '
    ';
        std::cout << path.find_last_of("ct") << '
    '; //找到config的c
    }

    返回:

    config
    6

    6.find_last_not_of

    寻找不等于给定字符序列中任何字符的最后字符。搜索只考虑区间 [0, pos] 。若区间中不存在这种字符,则返回 npos 。

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        const std::string path = "/root/config";
        std::cout << path.find_last_not_of("ctg") << '
    '; //找到config的i
    }

    返回10

    7.strchr

    定义于头文件 <cstring>,所以下面应该#include <cstring>,但是发现<string>也没事,不知道为什么!!!!!!!
    const char* strchr( const char* str, int ch );
          char* strchr(       char* str, int ch );

     str 所指向的字节字符串中寻找字符 static_cast<char>(ch) 的首次出现。 

    认为终止空字符是字符串的一部分,而且若搜索 '' 则能找到它。

    参数

    str - 指向待分析的空终止字节字符串的指针
    ch - 要搜索的字符

    返回值

    指向 str 找到的字符的指针,若未找到该字符则为空指针(NULL)

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        const char *str = "Try not. Do, or do not.There is no try.";
        char target = 'T';
        const char *result = str;
        while((result =std::strchr(result, target)) != NULL) {
            std::cout << "Found '" << target << "' starting at '" << result << "'
    ";
            ++result; //自增,继续寻找其他的target
        }
    }

    返回:

    Found 'T' starting at 'Try not. Do, or do not.There is no try.'
    Found 'T' starting at 'There is no try.'

    8.strrchr

    定义于头文件 <cstring>

    寻找 ch (转换到 char 后)在 str 所指向的空终止字节串中的最后出现。若搜索 '' ,则认为终止空字符为字符串的一部分,而且能找到。

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        char input[] = "/home/user/hello.c";
        char* output = std::strrchr(input, '/');
        if(output){
            std::cout << output+1 << '
    ';
        }
    }

    返回:

    hello.c

    9.strstr

    定义于头文件 <cstring>
    const char* strstr( const char* str, const char* target );
          char* strstr(       char* str, const char* target );

     str 所指的字节字符串中寻找字节字符串 target 的首次出现。不比较空终止字符。

    参数

    str - 指向要检验的空终止字节字符串的指针
    target - 指向要查找的空终止字节字符串的指针

    返回值

    指向 str 中寻获子串的首个字符的指针,或若找不到该字符则为 NULL 。若 target 指向空字符串,则返回 str 。

    例子:

    #include <string>
    #include <iostream>
    
    int main(){
        const char *str = "Try not. Do, or do not. There is no try.";
        const char *target = "not";
        const char *result = str;
        while((result = std::strstr(result, target)) != NULL){
            std::cout << "Found '" << target << "' starting at '" << result << "'
    ";
     
            // 自增 result ,否则会找到同一位置的目标
            ++result;
        }
    }

    返回:

    Found 'not' starting at 'not. Do, or do not. There is no try.'
    Found 'not' starting at 'not. There is no try.'
  • 相关阅读:
    整理+学习《骆昊-Java面试题全集(下)》
    整理+学习《骆昊-Java面试题全集(中)》
    Linux专家心目中的最佳Linux发行版有哪些?
    常用的Git Tips
    Python 3 加密简介
    LXD 2.0 系列(一):LXD 入门
    英特尔构建云集成编排工具
    Unix操作系统中UUCP知识详细讲解
    Windows 的 AD 域寄生于 Linux 机器
    Git秘籍:在 Git 中进行版本回退
  • 原文地址:https://www.cnblogs.com/wanghui-garcia/p/12468137.html
Copyright © 2011-2022 走看看