描述Given two strings A and B, whose alphabet consist only ‘0’ and ‘1’. Your task is only to tell how many times does A appear as a substring of B? For example, the text string B is ‘1001110110’ while the pattern string A is ‘11’, you should output 3, because the pattern A appeared at the posit
- 输入
- The first line consist only one integer N, indicates N cases follows. In each case, there are two lines, the first line gives the string A, length (A) <= 10, and the second line gives the string B, length (B) <= 1000. And it is guaranteed that B is always longer than A.
- 输出
- For each case, output a single line consist a single integer, tells how many times do B appears as a substring of A.
- 样例输入
-
3 11 1001110110 101 110010010010001 1010 110100010101011
- 样例输出
-
3 0 3
1 //Binary String Matching length (A) <= 10 length (B) <= 1000 2 #include <stdio.h> 3 #include <string.h> 4 5 #define TRUE 1 6 #define FALSE 0 7 8 #define SIZE_A 10 //A的最长长度为10 9 #define SIZE_B 1000 //B的最长长度为1000 10 11 int compare(char *p,char *q,int); //比较两个字符串是否相等 12 13 int main() 14 { 15 char array_a[SIZE_A]; 16 char array_b[SIZE_B]; 17 int num; //待处理数据的组数 18 int count = 0; //A串在B中出现的次数 19 char *p = 0,*q = 0; 20 21 scanf("%d", &num); 22 while(num > 0) //处理每一组串 23 { 24 int len_a,len_b; 25 int i = 0; 26 27 count = 0; 28 scanf("%s", array_a); 29 fflush(stdin); 30 scanf("%s", array_b); 31 //gets(array_a); //先接收子串a 32 //fflush(stdout); 33 //gets(array_b); //接收字符串b 34 35 len_a = strlen(array_a); //a和b的长度 36 len_b = strlen(array_b); 37 38 p = array_a; 39 q = array_b; 40 41 for(; i <= len_b - len_a; i ++) 42 { 43 if(compare(p,q,len_a) == TRUE) 44 count ++; 45 q ++; 46 } 47 printf("%d ", count); //输出结果 48 49 num --; 50 } 51 } 52 //比较两个字符串是否相等 53 int compare(char *p, char *q,int length) 54 { 55 int flag = TRUE; 56 int i = 0; 57 58 for(; i < length; i ++) 59 { 60 if((*p) != (*q)) 61 { 62 flag = FALSE; 63 break; 64 } 65 p ++; 66 q ++; 67 } 68 69 return flag; 70 }
这里可以使用strcmp来做。