在C语言中,要求编写程序在给定的字符串中查找指定的字符。

要求:(1)字符串采用直接初始化的方式处理 (2)通过scanf函数读入一个任意字符: (3)在字符串中查找该字符,如果存在该字符,输出该字符在字符串中第一次出现的位置,如果不存在该字符,则给出相应的说明信息。

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

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-20

通过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
*/

第2个回答  2019-12-19

原理类似于找素数,以下是具体代码(附注释):

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int SearchString(char s[], char d[]);

main()
{
char s[81];  //储存一串字符
char d[10];  //储存要查找的字符
int flag;
//输入一串字符
printf("Input a string:");
gets(s);
//输入想要查找的字符
printf("Input another string:");
gets(d);
//调用函数,输出结果
flag=SearchString(s,d);
if(flag==-1)
printf("Not found!\n");
else
printf("Searching results:%d\n",flag);

system("pause");
}

//函数功能:在字符数组s中查找子串d,返回d在s中首次出现的位置,若找不到,则返回-1
int SearchString(char s[], char d[])
{
int location=-1;
int i,j;
//第一层循环遍历被查找字符串
for(i=0;s[i]!='\0';i++)
{
//第二层循环遍历要查找的字符,若有不同的字符则退出该循环
for(j=0;d[j]!='\0';j++)
{
if(s[i+j]!=d[j])
break;
}
//判断第二层循环是否全部执行,若全部执行则表示字符相等,保存位置
if(d[j]=='\0')
{
location=i+1;
break;
}
}
return location;
}

第3个回答  2014-11-20
#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;
}
第4个回答  推荐于2017-10-02
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int mian(int argc, char **argv)
{
    char sPtr[20]="nozuonodie";
    char cTmp;
    char cPtr;
    int  iNum;
    
    scanf("%c", &cTmp);
    if (!(cPtr = strchar(sPtr, cTmp)))
    {
        iNum = cPtr - sPtr;
        // first appear position
        printf("iNum = %d", iNum);
    }
    else
    {
        printf("Not exist\n");
    }
    
    return 0;
}

本回答被提问者采纳
相似回答