1. 程式人生 > >C++ string字元中英文字母大小寫的轉換

C++ string字元中英文字母大小寫的轉換

c++中的string類物件並沒有自帶的方法進行字元大小寫轉換,進行大小寫轉換的方法很多,這裡我們提供一個通過algorithm中的transform函式對string物件進行字元的大小寫轉換。

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

using namespace std;

int main() 
{
    string src = "Hello World!";
    string dst;

    transform(src.begin(), src.end(), back_inserter(dst), ::toupper);
    cout << dst << endl;

    transform(src.begin(), src.end(), dst.begin(), ::tolower);
    cout << dst << endl;

	system("pause");
    return 0;
}

/*
輸出結果:
HELLO WORLD!
hello world!
*/

在程式的標頭檔案中包含algorithm,進行轉換的時候,直接使用transform函式
注意transform有四個輸入引數:

1:str.begin()字串的起始地址;
2:str.end()字串的終止地址;
3:str.begin()是轉換之後,輸出到原str字串的起始地址;
4:轉換操作,可以選擇toupper,tolower。