string轉化大小寫(C++)

如何將一個字符串轉換成大寫或者小寫?這是字符串匹配中常常須要作的事情,然而C++的Standard Library並無提供將std::string轉成大寫和小寫的功能,只有在提供將char轉成大寫(toupper)和小寫(tolower)的功能而已。
但咱們能夠利用STL的transform配合toupper/tolower,完成std::string轉換大(小)寫的功能,也看到 模版編程 的威力了,一個transform函數,能夠適用於任何類型,且只要本身提供 函數 ,就可完成任何Transform的動做。ios

C++編程

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
int main() {
    string s = "Clare";
    // toUpper
    transform(s.begin(), s.end(), s.begin(), ::toupper);
    // toLower
    //transform(s.begin(),s.end(),s.begin(), ::tolower);
    cout << s << endl;
}

C函數

#include <stdio.h>
#include <ctype.h>
int main() {
    char s[] = "Clare";
    int i = -1;
    while(s[i++]) 
        s[i] = toupper(s[i]);
    // s[i] = tolower(s[i]);
    puts(s);  
}
相關文章
相關標籤/搜索