编写程序,输入一个字符串,过滤掉所有非小写字母,得到由小写字母组成的字符串并输出。用C语言
时间: 2024-03-08 11:49:09 浏览: 24
好的,以下是C语言的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char s[100];
printf("请输入一个字符串:");
scanf("%s", s);
// 过滤非小写字母
char filtered[100];
int j = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (islower(s[i])) {
filtered[j++] = s[i];
}
}
filtered[j] = '\0';
printf("过滤后的字符串为:%s\n", filtered);
return 0;
}
```
这段代码首先定义了一个字符数组 `s`,用于存储用户输入的字符串。然后使用 `scanf` 函数从标准输入中读取用户输入的字符串。
接下来,我们定义了另一个字符数组 `filtered`,用于存储过滤后的字符串。我们使用一个循环遍历输入字符串中的每个字符,如果该字符是小写字母,则将其加入 `filtered` 中。
最后,我们在 `filtered` 的末尾添加一个空字符 `\0`,以表示字符串的结尾,并使用 `printf` 函数输出过滤后的字符串。
注意,这段代码中使用了 `<ctype.h>` 头文件中的 `islower` 函数,用于判断一个字符是否为小写字母。
相关问题
编写c语言程序,输入一个字符串,将其中的小写字母修改为大写字母,输出该字符串
以下是一个简单的C语言程序,可以实现将输入字符串中的小写字母转换为大写字母:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
}
printf("转换后的字符串为:%s", str);
return 0;
}
```
程序中使用了 `ctype.h` 头文件中的 `islower()` 和 `toupper()` 函数,分别用于判断字符是否为小写字母和将小写字母转换为大写字母。程序首先使用 `fgets()` 函数从标准输入中读取一行字符串,并将其存储在字符数组 `str` 中。然后使用循环遍历字符串中的每个字符,如果该字符为小写字母,则使用 `toupper()` 函数将其转换为大写字母。最后,使用 `printf()` 函数输出转换后的字符串。
用c语言编写一个程序,输入一个字符串,删除字符串中所有的小写字母“c”。
以下是一个简单的C语言程序,可以实现输入一个字符串,删除其中所有的小写字母"c":
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, j;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for(i = j = 0; i < strlen(str); i++)
{
if(str[i] != 'c' && str[i] != 'C')
{
str[j++] = str[i];
}
}
str[j] = '\0';
printf("删除小写字母c后的字符串为:%s\n", str);
return 0;
}
```
该程序使用了一个for循环,遍历输入的字符串,将非小写字母"c"的字符保存到新的字符串中,最后输出删除小写字母"c"后的字符串。请注意,由于C语言中的字符串是以null字符('\0')作为结尾的,因此在将新字符串赋值给原始字符串时,需要在最后添加一个null字符。