C语言把一个字符串中的大写字母改成小写字母,其他字符保持不变
时间: 2025-02-16 21:16:12 浏览: 44
在C语言中,可以使用标准库函数`tolower()`和`toupper()`来转换字母的大小写,但是这两个函数只能处理单个字符。如果你想将整个字符串中的大写字母转化为小写,而其他字符不变,你需要遍历字符串并逐个应用这个转换。下面是一个简单的示例,使用循环和`tolower()`函数:
```c
#include <ctype.h> // 包含转义函数头文件
#include <stdio.h>
void convert_to_lowercase(char *str) {
for (int i = 0; str[i] != '\0'; i++) { // 遍历直到遇到字符串结束符'\0'
if (isupper(str[i])) { // 检查当前字符是否为大写
str[i] = tolower(str[i]); // 转换为小写
}
}
}
int main() {
char input[] = "Hello World! This is a Test.";
convert_to_lowercase(input);
printf("转换后的字符串: %s\n", input);
return 0;
}
```
当你运行上面的程序,输入的字符串"Hello World! This is a Test."将会变为"hello world! this is a test."。
相关问题
c语言把一个字符串中的大写字母改成小写字母,其他字符不变。代码
可以使用以下的 C 语言代码来实现:
```
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:\n");
fgets(str, 100, stdin); // 从标准输入读入字符串
for (int i = 0; i < strlen(str); i++) {
if (isupper(str[i])) { // 判断当前字符是否为大写字母
str[i] = tolower(str[i]); // 转换为小写字母
}
}
printf("转换后的字符串为:%s\n", str);
return 0;
}
```
在这个程序中,我们首先通过 `fgets()` 函数从标准输入读入一个字符串,并存储到 `str` 数组中。然后使用一个 `for` 循环遍历字符串中的每一个字符,如果当前字符是大写字母,就使用 `tolower()` 函数将其转换为小写字母。最后再使用 `printf()` 函数将转换后的字符串输出到屏幕上。
C语言统计输入的字符串中大写字母和小写字母的个数
可以使用C语言的字符操作函数isupper和islower来判断一个字符是否为大写字母或小写字母,然后统计出现次数即可。
以下是示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int upper_count = 0, lower_count = 0, i = 0;
printf("请输入字符串:");
fgets(str, 100, stdin);
while (str[i] != '\0') {
if (isupper(str[i])) {
upper_count++;
} else if (islower(str[i])) {
lower_count++;
}
i++;
}
printf("大写字母个数:%d\n", upper_count);
printf("小写字母个数:%d\n", lower_count);
return 0;
}
```
在这个示例中,我们使用了fgets函数来从标准输入读取字符串,然后遍历字符串中的每个字符,使用isupper和islower函数判断是否为大写字母或小写字母,最后统计出现次数并输出。
阅读全文
相关推荐
















