如何在 C++ 中將 std::string 轉換為小寫?


在本節中,我們將瞭解如何將 C++ 字串中的所有字母轉換為小寫字母。為此,我們必須使用 transform 函式。此 transform 函式存在於演算法庫中。

transform 函式獲取字串的起始指標和字串的結束指標。它還獲取字串的開頭來儲存結果,然後第四個引數為 ::tolower。這有助於將字串轉換為小寫字串。如果我們想要將某個字串轉換為大寫字串,則可以使用相同的方法。

示例程式碼

 線上演示

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

int main() {
   string my_str = "Hello WORLD";

   cout << "Main string: " << my_str << endl;
   transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower);

   cout << "Converted String: " << my_str;
}

輸出

Main string: Hello WORLD
Converted String: hello world

更新於: 30-Jul-2019

8K+ 瀏覽次數

開啟你的 職業生涯

完成課程獲得認證

開始
廣告