名稱空間
變體
操作

std::toupper

來自 cppreference.com
< cpp‎ | string‎ | byte
在標頭檔案 <cctype> 中定義
int toupper( int ch );

根據當前安裝的 C 語言環境定義的字元轉換規則,將給定字元轉換為大寫。

在預設的 "C" 語言環境中,以下小寫字母 abcdefghijklmnopqrstuvwxyz 將被替換為相應的大寫字母 ABCDEFGHIJKLMNOPQRSTUVWXYZ

目錄

[編輯] 引數

ch - 要轉換的字元。如果 ch 的值不能表示為 unsigned char 且不等於 EOF,則行為未定義。

[編輯] 返回值

轉換後的字元,如果當前 C 語言環境未定義大寫版本,則為 ch

[編輯] 注意

<cctype> 中的所有其他函式一樣,如果引數的值既不能表示為 unsigned char 也不等於 EOF,則 std::toupper 的行為未定義。為了安全地將這些函式與普通 char(或 signed char)一起使用,引數應首先轉換為 unsigned char

char my_toupper(char ch)
{
    return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}

同樣,當迭代器值型別為 charsigned char 時,它們不應直接與標準演算法一起使用。相反,應首先將值轉換為 unsigned char

std::string str_toupper(std::string s)
{
    std::transform(s.begin(), s.end(), s.begin(),
                // static_cast<int(*)(int)>(std::toupper)         // wrong
                // [](int c){ return std::toupper(c); }           // wrong
                // [](char c){ return std::toupper(c); }          // wrong
                   [](unsigned char c){ return std::toupper(c); } // correct
                  );
    return s;
}

[編輯] 示例

#include <cctype>
#include <climits>
#include <clocale>
#include <iostream>
#include <ranges>
 
int main()
{
    for (auto bd{0}; unsigned char lc : std::views::iota(0, UCHAR_MAX))
        if (unsigned char uc = std::toupper(lc); uc != lc)
            std::cout << lc << uc << (13 == ++bd ? '\n' : ' ');
    std::cout << "\n\n";
 
    unsigned char c = '\xb8'; // the character ž in ISO-8859-15
                              // but ¸ (cedilla) in ISO-8859-1
 
    std::setlocale(LC_ALL, "en_US.iso88591");
    std::cout << std::hex << std::showbase;
    std::cout << "in iso8859-1, toupper('0xb8') gives " << std::toupper(c) << '\n';
    std::setlocale(LC_ALL, "en_US.iso885915");
    std::cout << "in iso8859-15, toupper('0xb8') gives " << std::toupper(c) << '\n';
}

輸出

aA bB cC dD eE fF gG hH iI jJ kK lL mM
nN oO pP qQ rR sS tT uU vV wW xX yY zZ
 
in iso8859-1, toupper('0xb8') gives 0xb8
in iso8859-15, toupper('0xb8') gives 0xb4

[編輯] 另請參閱

將字元轉換為小寫
(函式) [編輯]
使用區域設定的 ctype 刻面將字元轉換為大寫
(函式模板) [編輯]
將寬字元轉換為大寫
(函式) [編輯]
C 文件 用於 toupper

[編輯] 外部連結

1.  ISO/IEC 8859-1。來自維基百科。
2.  ISO/IEC 8859-15。來自維基百科。