遍歷字符串每個字符,調用 toupper()(定義於 )轉換為大寫,原地修改字符數組。
#include\ #include \ #include \ #include \ int main(void) {\ int length, i;\ char string[20] = "this is a string";\ \ length = strlen(string);\ for (i = 0; i < length; ++i) {\ string[i] = toupper(string[i]);\ }\ \ printf("%s\\n", string);\ system("pause"); // Windows 下暫停控制台\ return 0;\ }
strlen 獲取字符串長度(不含結束符 \\0)。toupper(int c):參數為 int,實際接受 unsigned char 或 EOF;若參數為小寫字母返回對應大寫,否則原值返回。安全性:對非字母字符(空格、數字、標點)無副作用。string[i],無需額外緩衝區。system("pause") 僅 Windows 有效,跨平台建議用 getchar() 替代。THIS IS A STRING
#include\ #include \ void str_toupper(char *str) {\ for (; *str; ++str) *str = toupper((unsigned char)*str);\ }\ void str_tolower(char *str) {\ for (; *str; ++str) *str = tolower((unsigned char)*str);\ }\ void str_toggle_case(char *str) {\ for (; *str; ++str) {\ if (islower((unsigned char)*str)) *str = toupper(*str);\ else if (isupper((unsigned char)*str)) *str = tolower(*str);\ }\ }
(unsigned char) 避免負值字符導致未定義行為。| 函數 | 頭文件 | 功能 |
|---|---|---|
| toupper | ctype.h | 單字符轉大寫 |
| tolower | ctype.h | 單字符轉小寫 |
| strupr | string.h (非標準) | 字符串轉大寫 (MSVC) |
| strlwr | string.h (非標準) | 字符串轉小寫 (MSVC) |