C++ string大小寫轉換


#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(){
    string input;
    string lower,upper;
    cin >> input;

    lower.resize(input.size()); 
    upper.resize(input.size());

    transform(input.begin(), input.end(), lower.begin(), ::tolower);
    transform(input.begin(), input.end(), upper.begin(), ::toupper);
    //transform(input.begin(), input.end(), upper.begin(), (int (*)(int))std::toupper);

    cout << "Tolower Result :" << endl << lower << endl;
    cout << "Toupper Result :" << endl << upper << endl;

    return 0;
}

Q1:為什么用 ::tolower 呢?

經過查閱C++標准庫(一、二),我得到了結果,tolower和toupper 分別在兩個地方定義了。一個是 std::tolower ,一個是在 cctype中定義的。

如果單純使用 tolower ,編譯器會使用去加載這個 std::tolower ,而 std::tolower的原型是: charT toupper (charT c, const locale& loc); ,不符合transform函數的第四個參數。因此我們需要給他變型一下。也就是上面被注釋掉的代碼。如果要使用 cctype中的 tolower ,就直接用全局定義 :: ,即可。

Q2:resize又是干什么?

目標容器得有一定容量容得下源容器。
說一下這個大小寫轉化的應用,可以做忽略大小寫的查找。都轉換成小寫,然后find。

bool find_pattern(string input,string pattern){
    string::size_type result = input.find(pattern);
    if (result != string::npos)
        return true;
    else
        return false;
 
}

轉載:說一下這個大小寫轉化的應用,可以做忽略大小寫的查找。都轉換成小寫,然后find。

bool find_pattern(string input,string pattern){
    string::size_type result = input.find(pattern);
    if (result != string::npos)
        return true;
    else
        return false;

}

轉載:https://www.ijophy.com/2014/11/cpp-string-tolower-toupper.html


免責聲明!

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



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