c判断是不是子串

 1 #include <stdio.h>
 2 #include <string.h>//添加字符串头文件
 3 
 4 int Subsequence(char s[], char t[]) 
 5 {
 6     int m,n,i,j;
 7     n = strlen(s);       //n表示序列S的长度
 8     m = strlen(t);       //m表示序列T的长度
 9     i=0;
10     j=0;
11     if (m>n)  
12     return 0;                         //T不是S的子序列
13     while ((i<=m)&&(j<=n))
14         {
15         if(t[i]==s[j])
16 //序列T中第i个元素与序列S中第j个元素相等
17             i=i+1;
18             j=j+1;
19            }
20    if (strstr(s,t)!=NULL)
21     return 1;      //T是S的子序列
22     return 0;
23 }
24 
25 
26 int main() 
27 {
28     int Subsequence(char s[], char t[]);
29     char s[30],t[30];
30     int n,m;
31     
32     printf("**************************************************\n"); 
33     printf("               子 串 判 定 算 法\n"); 
34     printf("**************************************************\n\n"); 
35 
36     printf("您要在多少组序列中进行判定,请输入(1~100):");  
37     scanf("%d",&n);
38     printf("\n");       
39     
40     m=1;
41     while(n--)  
42     {
43         
44         printf("请输入第%d组待匹配序列S:",m);  
45         scanf("%s",s); 
46         printf("请输入第%d组待匹配序列T:",m);  
47         scanf("%s",t); 
48         if(Subsequence(s,t))
49         printf("序列T(%s)是序列S(%s)的子串。\n\n",t,s);  
50         else  
51         printf("序列T(%s)不是序列S(%s)的子串。\n\n",t,s); 
52         m++; 
53     }
54 }  

或将if (strstr(s,t)!=NULL);改一下

 1 for(k=0;n-k>=m;k++)
 2 {
 3      if(s[k]==t[0])
 4 {
 5      for(q=0;q<m;q++)
 6 if(s[k+q]!=t[q])
 7 break;
 8 if(q==m)
 9 return k+1;
10 }
11 }

子串要求连续的出现在母串中;

strstr函数:strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。

str1: 被查找目标 string expression to search.
str2: 要查找对象 The string expression to find.
返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。

 

posted @ 2016-11-07 17:26  OVER_AGAIN_THIS  阅读(1175)  评论(0编辑  收藏  举报