编写一个程序,在已知字符串中查找某个字符首次出现的位置,若字符串中没有该字符,给出相应信息。

请写出详细代码,谢谢

#include <stdio.h>
#define Maxsize 100
int make_index(char *p,char found)
{
int index=0;
while(*p&&*p++!=found)
index++;
if(*p)
return index;
return -1;
}
int main()
{
int add;
char found;
char char_array[Maxsize];
printf("输入字符串\n");
gets(char_array);
printf("输入你想查找的字符:\n");
found=getchar();
add=make_index(char_array,found);
if(add>=0)
printf("该字符首次出现的下标是:%2d\n",add);
else
printf("无该字符\n");
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-12-17
#include <string.h>
#include <stdio.h>

int main(void)
{
char string[15];
char *ptr, c = 'r';

strcpy(string, "This is a string");
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
return 0;
}
相似回答