大小写的转化
利用 ASCII 码值的差值进行转换
- 原理:在 ASCII 码表中,大写字母和小写字母的编码是有规律的。小写字母比对应的大写字母的 ASCII 码值大 32 。例如,‘A’ 的 ASCII 码值是 65 ,‘a’ 的 ASCII 码值是 97 。所以可以通过对字符的 ASCII 码值进行加减操作来实现大小写转换。
- 代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <stdio.h> int main() { char ch = 'A'; if (ch >= 'A' && ch <= 'Z') { ch = ch + 32; } printf("转换后的字符: %c\n", ch);
char ch2 = 'b'; if (ch2 >= 'a' && ch2 <= 'z') { ch2 = ch2 - 32; } printf("转换后的字符: %c\n", ch2); return 0; }
|
使用标准库函数 tolower()
和 toupper()
- 原理:C 语言的标准库
<ctype.h>
提供了 tolower()
和 toupper()
函数来进行字符大小写转换。tolower()
函数会将给定的字符转换为小写形式(如果该字符是大写字母 ),toupper()
函数会将给定的字符转换为大写形式(如果该字符是小写字母 )。如果字符本身不是字母,函数会直接返回原字符。
- 代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> #include <ctype.h> int main() { char ch = 'A'; ch = tolower(ch); printf("转换后的字符: %c\n", ch);
char ch2 = 'b'; ch2 = toupper(ch2); printf("转换后的字符: %c\n", ch2); return 0; }
|
对字符串中的字符进行大小写转换
如果要对字符串中的所有字符进行大小写转换,可以结合循环和上述方法来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <stdio.h> #include <string.h> int main() { char str[100] = "Hello World"; int len = strlen(str); for (int i = 0; i < len; i++) { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = str[i] + 32; } else if (str[i] >= 'a' && str[i] <= 'z') { str[i] = str[i] - 32; } } printf("转换后的字符串: %s\n", str); return 0; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <stdio.h> #include <string.h> #include <ctype.h> int main() { char str[100] = "Hello World"; int len = strlen(str); for (int i = 0; i < len; i++) { if (isupper(str[i])) { str[i] = tolower(str[i]); } else if (islower(str[i])) { str[i] = toupper(str[i]); } } printf("转换后的字符串: %s\n", str); return 0; }
|