字符串查找子串

不调用任何系统函数,实现一个字符串查找子串的函数,如果包含字串,则返回该字符串的位置值,如果不包含,则返回-1

 1 //不调用任何系统函数,实现一个字符串查找子串的函数,如果包含字串,则返回该字符串的位置值,如果不包含,则返回-1
 2 #include "stdafx.h"
 3 #include <string.h>
 4 
 5 //方法1
 6 int search_max_substr1(const char *str1,const char *str2)//在str1中查找子串str2
 7 {
 8     int pos=0,k=0,staic=0;
 9     int str1_len=strlen(str1);
10     int str2_len=strlen(str2);
11     for(int i=0;i<str1_len;i++)
12     {
13         for(int j=0;j<str2_len;j++)
14         {
15             if (str1[i]==str2[j])
16             {
17                 staic=1;
18                 k=1;
19                 pos=i;
20                 while((str1[i+k]==str2[j+k])&&(str1[i+k]!='\0')&&(str2[j+k]!='\0'))
21                     {
22                         k++;
23                     }
24                 break;
25             }
26         }
27         if (staic==1)
28             break;
29     }
30     if(k==str2_len) //若在str1中找到子串str2,返回子串在str1中的位置
31         return pos;
32     else
33         return -1;
34 }
35 
36 //方法2
37 int search_max_substr2(const char *str1,const char *str2)
38 {
39     int len1=strlen(str1),len2=strlen(str2);
40     int i=0,j=0;
41     while (i<len1&&j<len2)
42     {
43         if ( *(str1+i)==*(str2+j) )
44         {
45             int pos=i;
46             int ii=i+1;
47             int jj=j+1;
48             while ((ii<len1)&&(jj<len2))
49             {
50                 if(*(str1+ii)==*(str2+jj))
51                 {
52                     ii++;
53                     jj++;
54                 }
55                 else 
56                 {
57                     break;
58                 }
59             }
60         if(jj==len2)//查找成功
61             return pos;
62         
63         }
64         else 
65         {
66             i++;
67         }
68     }
69     return -1;
70 }
71 
72 void main()
73 {
74     int x;
75     //x=search_max_substr1("abcdegf","cde");
76     x=search_max_substr2("abcdegf","cde");
77     if (x!=-1)
78         printf("succed! location=%d",x);
79     else 
80         printf("-1");
81 }

 

 

 

 

转载于:https://www.cnblogs.com/xingele0917/archive/2012/10/04/2711615.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值