C语言函数应用:编写一个从字符串的指定位置开始查找给定的字符,返回该字符在该字符串中第一次出现位置的函数MyInstr,实现程序功能。
问题描述:
【问题描述】
编写一个从字符串的指定位置开始查找给定的字符,返回该字符在该字符串中第一次出现位置的函数MyInstr,实现程序功能。在主函数中通过调用MyInstr函数,实现对于用户输入的内容是否含有非法*号的检查。
答
输入怎么没看到指定位置呢?
#include <stdio.h>
int MyInstr(char *s,int pos ,char c)
{
int i=0;
while(s[i] ! = 0)
{
if(i>=pos && s[i] == c)
return i;
i++;
}
return -1;
}
int main()
{
char s[100];
int pos;
char c;
gets(s);
scanf("%d %c",&pos,&c);
pos = MyInstr(s,pos-1,c);
if(pos < 0)
printf("没有找到非法字符%c",c);
else
printf("该字符串的%d位置有非法字符%c",pos+1,c);
return 0;
}