您的位置:首页 > 其它

字符数组-返回字符串中的某个子串的开始位置,不使用string头文件-C

2014-09-06 21:40 288 查看
简单的来讲就是把字符串进行比较,从第一个相同的位置开始,之后逐个比对,直到不相同为止,此时比较相同字符数目与子串长度的关系,相同则返回第一个相同位置,否则返回-1

#include<stdio.h>

int find_substr(char *mainstr,char *substr);

int main(void)
{
if(find_substr("C is fun!","is")==-1)
{
printf("substr is not found!\n");
}
else
{
printf("substr is found!\n");
}
return 0;
}

int find_substr(char *mainstr,char *substr)
{
char *temp=substr;
int size=0;

while(*temp)
{
++size;
++temp;
}

int no=0;

while(*substr!=*mainstr)
{
++no;
++mainstr;
}

int index=0;

while(*(substr++)==*(mainstr++))
{
++index;
}

if(index==size)
{
return no;
}
else
{
return -1;
}
}


书中例子:

#include<stdio.h>

int find_substr(char *s1,char *s2);

int main(void)
{
if(find_substr("C is fun!","is")==-1)
{
printf("substr is not found!\n");
}
else
{
printf("substr is found!\n");
}
return 0;
}

int find_substr(char *s1,char *s2)
{
register int t;
char *p,*p2;

for(t=0;s1[t];++t)
{
p=&s1[t];
p2=s2;

while(*p2 && *p2==*p)
{
++p;
++p2;
}
if(! *p2)
{
return t;
}
}
return -1;
}


例中的思路是:

将s2与s1进行比较,到s2结尾了或是二者不相同了为止,此时判断,若是因为s2结尾了,那么返回开始比较时的s1串中的字符位置,否则就是因为二者不相同而结束,返回-1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐