编写一个函数,实现从一个字符串中,查找另一个字符串的位置(笔试题) 例如int func("12345", "34")返回值为2,即在2号位置找到字符串“34”。

来源:互联网 发布:手机淘宝怎么取消差评 编辑:程序博客网 时间:2024/06/05 19:10

运用strncmp函数,很容易就找到另一个字符串的位置。


#include <stdio.h>

#include <string.h>


int main()
{
char a[100] = {0};
char b[10] = {0};
char *p = a;
char *s = b;
char *temp;
temp = p;


printf("please input two strings(以空格间开):\n");
    scanf("%s %s",a,b);



while(*temp != '\0' && strlen(temp) > strlen(s))
{
if(strncmp(temp,s,strlen(s)) == 0)//判断temp前strlen(s)个长度的字符和s是否相同;
{
break;
}
else
{
temp++;//指向temp的下一个地址;
}
}
printf("%d\n",(temp - p));

return 0;
}
阅读全文
0 0