c++ string匹配能否忽略大小寫(xiě)

c++
小樊
81
2024-09-25 08:47:12

是的,C++中的string匹配可以忽略大小寫(xiě)??梢允褂肅++標(biāo)準(zhǔn)庫(kù)中的algorithm函數(shù)tolower()將字符串轉(zhuǎn)換為小寫(xiě),然后再進(jìn)行匹配。例如:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello World";
    string str2 = "hello world";
    transform(str1.begin(), str1.end(), str1.begin(), ::tolower); // 將str1轉(zhuǎn)換為小寫(xiě)
    transform(str2.begin(), str2.end(), str2.begin(), ::tolower); // 將str2轉(zhuǎn)換為小寫(xiě)
    if (str1 == str2) {
        cout << "Strings match, ignoring case." << endl;
    } else {
        cout << "Strings do not match." << endl;
    }
    return 0;
}

輸出結(jié)果為:

Strings match, ignoring case.

0