std::toupper
從 cppreference.com
在標頭 <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))); }
類似地,迭代器的值類型為 char 或 signed char 時,不應直接將它們用於標準算法。而是要首先轉換值為 unsigned char:
std::string str_toupper(std::string s) { std::transform(s.begin(), s.end(), s.begin(), // static_cast<int(*)(int)>(std::toupper) // 错误 // [](int c){ return std::toupper(c); } // 错误 // [](char c){ return std::toupper(c); } // 错误 [](unsigned char c){ return std::toupper(c); } // 正确 ); 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'; // ISO-8859-15 中的字符 ž // 但在 ISO-8859-1 中为 ¸ (下加符) std::setlocale(LC_ALL, "en_US.iso88591"); std::cout << std::hex << std::showbase; std::cout << "iso8859-1 中, toupper('0xb8') 得到 " << std::toupper(c) << '\n'; std::setlocale(LC_ALL, "en_US.iso885915"); std::cout << "iso8859-15 中, toupper('0xb8') 得到 " << 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 iso8859-1 中, toupper('0xb8') 得到 0xb8 iso8859-15 中, toupper('0xb8') 得到 0xb4
[編輯] 參閱
轉換字符為小寫 (函數) | |
用本地環境的 ctype 刻面將字符轉換成大寫 (函數模板) | |
轉換寬字符為大寫 (函數) | |
toupper 的 C 文檔
|
[編輯] 外部鏈接
1. | ISO/IEC 8859-1. From Wikipedia. |
2. | ISO/IEC 8859-15. From Wikipedia. |