用c语言写编写一个程序,输入一个字符串str(长度不超过30)和一个字符ch,通过指针查找、统计字符串str中字符ch出现的位置(区分大小写)。 【输入形式】 输入一个字符串str,以及一个字符ch 【输出形式】 若ch在str中存在,输出位置,位置之间以空格分隔 若ch在str中不存在,输出NULL 输出后面无换行符
时间: 2023-06-07 14:10:39 浏览: 311
您好,根据您的要求,我可以为您提供以下的C语言代码实现:
#include <stdio.h>
#include <string.h>
void search_char(char *str, char ch)
{
int len = strlen(str);
int i;
int found = 0;
for (i = 0; i < len; ++i) {
if (str[i] == ch) {
printf("%d ", i);
found = 1;
}
}
if (!found)
printf("NULL");
}
int main()
{
char str[31];
char ch;
scanf("%s %c", str, &ch);
search_char(str, ch);
return 0;
}
请注意,本程序仅限于根据您的要求进行实现,如果在实际应用中还需要考虑其他的异常情况,请自行进行检查和处理。如有任何疑问,欢迎随时向我提出。
相关问题
在c语言中,编写一个程序,输入一个字符串str和一个字符ch,通过指针查找,统计字符串str中ch出现的位置
下面是一个实现该功能的C语言程序:
```c
#include <stdio.h>
#include <string.h>
void find_char(const char *str, char ch, int *pos, int *count) {
int len = strlen(str);
*count = 0;
for (int i = 0; i < len; i++) {
if (str[i] == ch) {
pos[*count] = i;
(*count)++;
}
}
}
int main() {
char str[100];
char ch;
int pos[100];
int count = 0;
printf("请输入一个字符串:");
scanf("%s", str);
printf("请输入要查找的字符:");
scanf(" %c", &ch);
find_char(str, ch, pos, &count);
if (count == 0) {
printf("字符串中未找到该字符。\n");
} else {
printf("该字符在字符串中出现了%d次,位置分别为:\n", count);
for (int i = 0; i < count; i++) {
printf("%d ", pos[i]);
}
printf("\n");
}
return 0;
}
```
在程序中,我们定义了一个`find_char`函数,它接收一个字符串、一个字符、一个位置数组和一个计数器指针作为输入,通过指针查找字符串中指定字符的位置,并将位置存储在位置数组中,最后更新计数器指针的值为该字符在字符串中出现的次数。
在`main`函数中,我们先读入一个字符串和一个字符,然后调用`find_char`函数查找该字符在字符串中的位置,最后输出结果。
需要注意的是,在调用`scanf`函数读入字符时,我们需要在前面加上一个空格,以消耗掉之前输入时留下的换行符或空格。
编写一个程序,输入一个字符串str和一个字符ch,通过指针查找,统计字符串str中字符ch出现的位置
以下是一个C语言的示例程序,可以实现统计字符串str中字符ch出现的位置:
```c
#include <stdio.h>
#include <string.h>
void find_char(char *str, char ch, int *pos, int *count) {
int len = strlen(str);
*count = 0;
for (int i = 0; i < len; i++) {
if (*str == ch) {
pos[(*count)++] = i;
}
str++;
}
}
int main() {
char str[100];
char ch;
int pos[100], count;
printf("请输入字符串:");
scanf("%s", str);
printf("请输入要查找的字符:");
scanf(" %c", &ch);
find_char(str, ch, pos, &count);
if (count == 0) {
printf("未找到该字符\n");
} else {
printf("该字符出现的位置为:");
for (int i = 0; i < count; i++) {
printf("%d ", pos[i]);
}
printf("\n");
}
return 0;
}
```
程序中的`find_char`函数接受三个参数:字符串`str`、要查找的字符`ch`、和保存字符出现位置的数组`pos`。函数通过指针返回字符出现的次数`count`,并将每次出现的位置保存在`pos`数组中。
在`main`函数中,先使用`scanf`函数获取用户输入的字符串和字符。然后调用`find_char`函数查找字符,并根据返回的次数和位置数组输出结果。