编写程序实现在一个字符串中查找指定的字符(请用c语言作答)

编写程序实现在一个字符串中查找指定的字符,并输出指定的字符在字符串中出现的次数及位置,如果该字符串中不包含指定的字符,请输出提示信息。
1.定义两个一维数组,a字符数组用来存放字符串,b整数数组用来存放指定的字符在字符串中出现的位置(即对应的下标)。
2.定义i,j,m三个循环控制变量和一个标志变量flag,并初始化flag的值为0。
3.用scanf或者gets函数为字符数组赋一个字符串。
4.在循环中对字符数组的每个元素和指定字符ch进行匹配判断,如果相同,就把其下标依次存放在数组b中,并置flag的值为1。
5.循环退出后判断标志变量flag的值,如果仍为0,说明字符串中没出现指定的字符,否则,就输出该字符在字符串中出现的次数和位置。
最新回答
一身懵逼正气

2024-05-03 00:01:19

#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&lt;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&lt;stdio.h&gt;

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();

浓烈往事

2024-05-03 01:27:39

#include<stdio.h>
#include<string.h>
main()
{   char a[1000],ch;
    int b[1000],i,j,m,flag;
    while(1){
     scanf("%c",&ch);
     getchar();
     gets(a);
     flag=0;j=0;
     for(i=0;i<strlen(a);i++)
        if(a[i]==ch){
            b[j]=i;
            j++;
            flag=1;
   }
if(flag){
printf("%d次\n",j);
for(m=0;m<j;m++)
   printf("%4d",b[m]);
printf("\n\n");
}
else
    printf("没出现指定的字符\n\n");
}
}

如图所示,望采纳。。。。。。

追问
谢谢您的回答,可是输出的位置是b位置啊,不是a的位置
戏子人生。

2024-05-03 01:56:11

通过for循环依次遍历该字符串,如果存在就输出位置,不存在输出不存在该字符。

参考代码:

#include<stdio.h>
#include<string.h>
#define N 100
int main()
{
char a[N]="hello world!",ch;//初始化字符串 
int i,len,f=1;
scanf("%c",&ch);//输出查找字符 
len=strlen(a);
for(i=0;i<len;i++)//依次遍历字符串,判断是否存在 
if(a[i]==ch){//如果存在,输出位置 
printf("%d\n",i);
f=0;
}
if(f) //不存在输出 
printf("字符串中不存在该字符!\n");
return 0;
}
/*运行结果:
w
6
*/
依賴式颓废

2024-05-03 01:59:31

/*4.3*/
#include"stdio.h"
int main()
{
/*************************/
char a[1000],ch;
int b[1000],i,j,m;
int flag=0;j=0;
printf("请输入一个字符串:\n");
gets(a);
printf("请输入指定字符:\n");
scanf("%c",&ch);
for(i=0;a[i]!='\0';i++)
{
if(a[i]==ch)
{
b[j]=i;
j++;
flag=1;
}
}
if(flag)
{
printf("%d次\n",j);
for(m=0;m<j;m++)
printf("%4d",b[m]);
}
else
printf("没有出现指定字符\n");
/*************************/
return 0;
}
雨映燕帘

2024-05-03 00:08:00

#include <stdio.h>
int main()
{
char s[]="this is a test!" ;
char ch;
int i;
scanf("%c", &ch );
while( s[i] )
{
if ( s[i]==ch )
{
printf("%c at %d\n", ch, i+1 );
return 0;
}
i++;
}
printf("%c is not in '%s'\n", ch, s );
return -1;
}