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\n";
    }else{
        std::cout << "found: " << s.substr(n) << '\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\n";
    }else{
        std::cout << "found: \"" << s.substr(n) << "\" at " << n << '\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) << '\n'; //找到第一個出現o的位置,即Hello的o
    std::cout << str.find_first_of(search_str, 5) << '\n'; //找到從位置5開始第一個出現o的位置,即World的o
    std::cout << str.find_first_of(search_cstr) << '\n'; //尋找字符串中與str有重疊的字符的第一個位置
    std::cout << str.find_first_of(search_cstr, 5, 4) << '\n'; ////尋找字符串search_cstr[0:4]中與str從位置5開始有重疊的字符的第一個位置
    std::cout << str.find_first_of('x') << '\n'; //不存在,則返回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 << '\n';

    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 << '\n';
}

返回:

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 << '\n';
    std::cout << path.find_last_of("ct") << '\n'; //找到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") << '\n'; //找到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) 的首次出現。 

認為終止空字符是字符串的一部分,而且若搜索 '\0' 則能找到它。

參數

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 << "'\n";
        ++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 所指向的空終止字節串中的最后出現。若搜索 '\0' ,則認為終止空字符為字符串的一部分,而且能找到。

例子:

#include <string>
#include <iostream>

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

返回:

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 << "'\n";
 
        // 自增 result ,否則會找到同一位置的目標
        ++result;
    }
}

返回:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM