【C语言】标准库ctype.h:判断和映射字符。
#include <ctype.h>
标准库ctype.h:
函数中的参数:都是无符号字符转换为int值进行传递。
判断函数中的返回:若满足判断条件,返回非零值。若不满足判断条件,返回0。
转换函数中的返回:若有对应的大写/小写字母,返回转换后的字符(转换为int值)。若没有,返回原字符(转换为int值)。
// 部分函数举例
#include <ctype.h>
#include <stdio.h>
// 函数声明
char trans(char c);
int main(void)
{
char s[] = "year:2024.\tGOOD LUCK!\n";
int n = sizeof(s); // 获取字符串s的内存大小
int c; // 将要被判断的字符,转为int值作为参数传递给函数
char t[n]; // 字符串t,此处存储大小写转换后的字符串
for(int i = 0; i < n; i++)
{
c = s[i];
t[i] = c;
if(isdigit(c)) // 判断字符是否是数字
printf("index %d element:\"%c\" is digit\n", i, c);
else if(isalpha(c)) // 判断字符是否是字母
{
printf("index %d element:\"%c\" is ", i, c);
t[i] = trans(c); // 函数,大小写字母转换
}
else if(isspace(c)) // 判断字符是否是空白字符
printf("index %d element:\"%c\" is space\n", i, c);
else if(ispunct(c)) // 判断字符是否是标点符号
printf("index %d element:\"%c\" is punctuation\n", i, c);
}
printf("End: t = %s", t);
return 0;
}
char trans(char c)
{
if(islower(c)) // 判断字符是否是小写字母
{
printf("lowercase letter, convert to uppercase letter\n", c);
return toupper(c); // 小写字母转为大写字母
}
else if(isupper(c)) // 判断字符是否是大写字母
{
printf("uppercase letter, convert to lowercase letter\n", c);
return tolower(c); // 大写字母转为小写字母
}
}
// 结果:
index 0 element:"y" is lowercase letter, convert to uppercase letter
index 1 element:"e" is lowercase letter, convert to uppercase letter
index 2 element:"a" is lowercase letter, convert to uppercase letter
index 3 element:"r" is lowercase letter, convert to uppercase letter
index 4 element:":" is punctuation
index 5 element:"2" is digit
index 6 element:"0" is digit
index 7 element:"2" is digit
index 8 element:"4" is digit
index 9 element:"." is punctuation
index 10 element:" " is space
index 11 element:"G" is uppercase letter, convert to lowercase letter
index 12 element:"O" is uppercase letter, convert to lowercase letter
index 13 element:"O" is uppercase letter, convert to lowercase letter
index 14 element:"D" is uppercase letter, convert to lowercase letter
index 15 element:" " is space
index 16 element:"L" is uppercase letter, convert to lowercase letter
index 17 element:"U" is uppercase letter, convert to lowercase letter
index 18 element:"C" is uppercase letter, convert to lowercase letter
index 19 element:"K" is uppercase letter, convert to lowercase letter
index 20 element:"!" is punctuation
index 21 element:"
" is space
End: t = YEAR:2024. good luck!
补充:
if...else if...else...:若执行语句只有单行,可以省略大括号{ };若执行语句超过一行,必须使用大括号{ }。