如何用C语言写一段代码使得输入一个单词进行大小写转换
时间: 2024-11-06 11:14:52 浏览: 23
在C语言中,你可以通过标准库函数tolower()
和toupper()
来进行字符串的小写和大写转换。下面是一个简单的程序示例,它接收用户输入的一个单词,并将其转换为全小写或全大写:
#include <stdio.h>
#include <ctype.h> // 包含字符处理函数
// 将字符串转为全小写
void to_lower(char* str) {
while (*str != '\0') { // 遍历字符串直到结束
*str = tolower(*str); // 转换每个字符为小写
str++; // 移动指针到下一个字符
}
}
// 将字符串转为全大写
void to_upper(char* str) {
while (*str != '\0') {
*str = toupper(*str); // 转换每个字符为大写
str++;
}
}
int main() {
char input[100];
printf("请输入一个单词:");
fgets(input, sizeof(input), stdin); // 读取一行用户输入
// 检查输入是否以换行符结尾并移除
if (input[strlen(input)-1] == '\n')
input[strlen(input)-1] = '\0';
char lower_case[] = "to lower case: ";
char upper_case[] = "to upper case: ";
to_lower(input); // 转换成小写
printf("%s%s", lower_case, input);
to_upper(input); // 转换成大写
printf("\n%s%s", upper_case, input);
return 0;
}
在这个例子中,tolower()
和toupper()
函数分别用于将单个字符转换为相应的大写或小写。然后在main
函数中,我们先读取用户的输入,再分别调用to_lower()
和to_upper()
对输入进行转换。
相关推荐


















