溫馨提示×

怎樣處理c++ string匹配中的大小寫問題

c++
小樊
82
2024-09-25 07:34:13
欄目: 編程語言

在C++中處理string匹配中的大小寫問題時,可以采用以下幾種方法:

  1. 使用標準庫函數(shù) tolower 函數(shù)將字符串轉(zhuǎn)換為全小寫或全大寫。

    #include <algorithm>
    #include <cctype>
    
    std::string str = "Hello World";
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    
  2. 在比較字符串時忽略大小寫。

    #include <algorithm>
    
    std::string str1 = "Hello World";
    std::string str2 = "hello world";
    
    if (std::equal(str1.begin(), str1.end(), str2.begin(), [](char c1, char c2) {
        return std::tolower(c1) == std::tolower(c2);
    })) {
        // 字符串匹配成功
    }
    
  3. 使用正則表達式進行大小寫不敏感的匹配。

    #include <regex>
    
    std::string str = "Hello World";
    std::regex pattern("hello world", std::regex_constants::icase);
    
    if (std::regex_match(str, pattern)) {
        // 字符串匹配成功
    }
    

0