编写程序实现在一个字符串中查找指定的字符,并输出指定的字符在字符串中出现的次数及位置,如果该字符串中不包含指定的字符,请输出提示信息。
1.定义两个一维数组,a字符数组用来存放字符串,b整数数组用来存放指定的字符在字符串中出现的位置(即对应的下标)。
2.定义i,j,m三个循环控制变量和一个标志变量flag,并初始化flag的值为0。
3.用scanf或者gets函数为字符数组赋一个字符串。
4.在循环中对字符数组的每个元素和指定字符ch进行匹配判断,如果相同,就把其下标依次存放在数组b中,并置flag的值为1。
5.循环退出后判断标志变量flag的值,如果仍为0,说明字符串中没出现指定的字符,否则,就输出该字符在字符串中出现的次数和位置。
#include<stdio.h>
int main()
{
int i,index,count;
char a,ch,str[80];
scanf("%c\n",&a);
i=0;
index=-1;
count=0;
ch=getchar();
for(i=0;ch!='\n';i++){
str<i>=ch;
count++;
ch=getchar();
}
for(i=0;i<count;i++)
if(a==str<i>)
index=i;
if(index!=-1)
printf("index=%d",index);
else
printf("Not Found");
return 0;
}
getchar()用法:
getchar()函数的作用是从计算机终端(一般为键盘)输入一个字符。getchar()函数只能接收一个字符,其函数值就是从输入设备得到的字符。
例:
#include<stdio.h>
int main(void)
{
int c;
/*Note that getchar reads from stdin and
is line buffered;this means it will
not return until you press ENTER.*/
while((c=getchar())!='\n')
printf("%c",c);
return 0;
}
注:可以利用getchar()函数让程序调试运行结束后等待编程者按下键盘才返回编辑界面,用法:在主函数结尾,return 0;之前加上getchar();
如图所示,望采纳。。。。。。
追问谢谢您的回答,可是输出的位置是b位置啊,不是a的位置
本回答被提问者采纳通过for循环依次遍历该字符串,如果存在就输出位置,不存在输出不存在该字符。
参考代码:
#include<stdio.h>