码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-06 22:26:43      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   for   文件   div   

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

 1 #include<stdio.h>
 2 
 3 int find_substr(char *mainstr,char *substr);
 4 
 5 int main(void)
 6 {
 7     if(find_substr("C is fun!","is")==-1)
 8     {
 9         printf("substr is not found!\n");
10     }
11     else
12     {
13         printf("substr is found!\n");
14     }
15     return 0;
16 }
17 
18 int find_substr(char *mainstr,char *substr)
19 {
20     char *temp=substr;
21     int size=0;
22 
23     while(*temp)
24     {
25         ++size;
26         ++temp;
27     }
28 
29     int no=0;
30 
31     while(*substr!=*mainstr)
32     {
33         ++no;
34         ++mainstr;
35     }
36 
37     int index=0;
38 
39     while(*(substr++)==*(mainstr++))
40     {
41         ++index;
42     }
43 
44     if(index==size)
45     {
46         return no;
47     }
48     else
49     {
50         return -1;
51     }
52 }

 

书中例子:

 1 #include<stdio.h>
 2 
 3 int find_substr(char *s1,char *s2);
 4 
 5 int main(void)
 6 {
 7     if(find_substr("C is fun!","is")==-1)
 8     {
 9         printf("substr is not found!\n");
10     }
11     else
12     {
13         printf("substr is found!\n");
14     }
15     return 0;
16 }
17 
18 int find_substr(char *s1,char *s2)
19 {
20     register int t;
21     char *p,*p2;
22 
23     for(t=0;s1[t];++t)
24     {
25         p=&s1[t];
26         p2=s2;
27 
28         while(*p2 && *p2==*p)
29         {
30             ++p;
31             ++p2;
32         }
33         if(! *p2)
34         {
35             return t;
36         }
37     }
38     return -1;
39 }

例中的思路是:

将s2与s1进行比较,到s2结尾了或是二者不相同了为止,此时判断,若是因为s2结尾了,那么返回开始比较时的s1串中的字符位置,否则就是因为二者不相同而结束,返回-1;

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

标签:style   blog   color   io   使用   ar   for   文件   div   

原文地址:http://www.cnblogs.com/lhyz/p/3959848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!