行业知识
【C语言】五种方法实现C语言中大小写字母的转化
2026-11-28 12:16:34
来源:互联网转载
文章目录
- tolower/toupper函数
- tolower
- toupper
- ASCII码关系
- 位操作
- 宏定义
- 小巧第五位
- ���结
tolower/toupper函数
tolower
tolower函数是C标准库中用于将字母从大写转换为小写的函数。
函数原型:
int tolower(int c);c: 需要转换的字符,必须是unsigned char类型或可隐式转换为unsigned char类型的值。
返回值:
返回转换后的小写字符。如果c不是一个字母,则返回原值c。
返回值类型为int,这是为了能够返回任何可能的字符值。
注意:
c必须是unsigned char类型或能隐式转换为unsigned char,如char、int等。
返回值类型为int,是为了能够返回任何可能的字符值,包括非字母字符本身。
如果c不是一个字母,函数直接返回c而不进行转换。
代码:
# define _CRT_SECURE_NO_WARNINGS 1#include #include int main() { char uppercase = 'A'; char lowercase = tolower(uppercase); printf("%c 转为小写是:%c\n", uppercase, lowercase); return 0;}toupper
toupper函数是C标准库中用于将字母从小写转换为大写的函数。
int toupper(int c);
和tolower函数一样:
-
参数c类型为int,需要转换的字符可以隐式转换为unsigned char
-
返回值类型为int,返回转换后的大写字符或原字符c如果c不是字母
toupper函数和tolower函数的参数和返回值类型是完全相同的:
int tolower(int c);
int toupper(int c);
两者都以int类型作为参数和返回值,目的是为了能处理任何可能的字符值。
#include #include int main() { char lowercase = 'a'; char uppercase = toupper(lowercase); printf("%c 转为大写是: %c\n", lowercase, uppercase); return 0;}ASCII码关系
通过ASCII码表来进行大小写字母的转换。ASCII码表中小写字母的范围是97到122,大写字母的范围是65到90,它们之间相差32。因此,可以通过加上或者减去32来进行大小写字母的转换。
#include char to_uppercase(char c) { if (c >= 'a' && c // 如果是小写字母,则将ASCII码值减去32转换为大写字母 return c - 32; } else { return c; }}char to_lowercase(char c) { if (c = 'A' && c // 如果是大写字母,则将ASCII码值加上32转换为小写字母 return c + 32; } else { return c; }}int main() { for (char lowercase = 'a'; lowercase char uppercase = to_uppercase(lowercase); printf("%c 小转大: %c\n", lowercase, uppercase); } for (char uppercase2 = 'A'; uppercase2 char lowercase2 = to_lowercase(uppercase2); printf("%c 大写转小写: %c\n", uppercase2, lowercase2); } return 0;} if (c = 'a' && c if (c = 'A' && c char c = 'A';c = TOLOWER(c); // c becomes 'a'printf("%c\n", c);char d = 'a';d = TOUPPER(d); // d becomes 'A'printf("%c\n", d);} // 如果字符是小写字母,将第5位(32)置为0,即转换为大写字母 return (c & 0xdf);} // 如果字符是大写字母,将第5位(32)置为1,即转换为小写字母 return (c | 0x20);} char lowercase = 'l'; char uppercase = to_uppercase(lowercase); printf("%c converted to uppercase is: %c\n", lowercase, uppercase); char uppercase2 = 'G'; char lowercase2 = to_lowercase(uppercase2); printf("%c converted to lowercase is: %c\n", uppercase2, lowercase2); return 0;}
-