请用C语言编写如下程序:定义一个有80个元素的字符数组,从键盘输入一串字符,将其中的大写字母转换为小写字母,而将原来为小写的字母转换为大写字母,其他字符不变。
时间: 2023-06-09 20:03:19 浏览: 66
以下是代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[80];
printf("请输入一串字符:\n");
fgets(str, 80, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
else if (isupper(str[i])) {
str[i] = tolower(str[i]);
}
}
printf("转换后的字符串为:%s", str);
return 0;
}
```
输入一串字符后,程序会遍历字符数组,利用 `islower()` 和 `isupper()` 函数判断每个字符的大小写,然后再利用 `toupper()` 和 `tolower()` 函数转换大小写,最后输出转换后的字符串。
注:如果输入的字符串长度超过了 80,则可能出现问题。
相关问题
c语言写一段程序,要求:定义一个有80个元素的字符数组,从键盘输入一串字符,将其中的大写字母转变为小写字母,将原来的小写字母转变为大写字母,其他字符不变。
好的,以下是程序代码:
```
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[80];
int i, len;
printf("请输入一段字符串:\n");
fgets(str, 80, stdin);
len = strlen(str);
for(i=0; i<len; i++) {
if(isupper(str[i])) {
putchar(tolower(str[i]));
}
else if(islower(str[i])) {
putchar(toupper(str[i]));
}
else {
putchar(str[i]);
}
}
return 0;
}
```
7. 定义一个有80个元素的字符数组,从键盘输入一串字符,将其中的大写字母转换为小写字母,而将原来为小写的字母转换为大写字母,其他字符不变。用c语言编写
回答:
下面是代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[80];
int i;
printf("请输入一串字符:\n");
fgets(str, 80, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isupper(str[i]))
str[i] = tolower(str[i]);
else if (islower(str[i]))
str[i] = toupper(str[i]);
}
printf("转换后的字符串为:%s", str);
return 0;
}
```
首先定义了一个长度为80的字符数组str,用于存放从键盘输入的字符串。然后使用fgets函数从标准输入(即键盘)读入一行字符串,存放到str中。
接下来用循环遍历每一个字符,使用isupper函数判断当前字符是否为大写字母,如果是则用tolower函数转换为小写字母;使用islower函数判断当前字符是否为小写字母,如果是则用toupper函数转换为大写字母;如果既不是大写字母也不是小写字母,则不做处理。
最后输出转换后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)