Binary String Matching(C++)

题目描述:
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

翻译如下:

题目描述:
给定两个字符串A和B,其字母表仅包含’0’和’1’。你的任务只是告诉A多少次出现在B的子串中?例如,文本字符串B是’1001110110’,而模式字符串A是’11’,你应该输出3,因为模式A出现在文本字符串B里面三次
输入描述:
第一行仅包含一个整数N,表示N个案例。在每种情况下,有两行,第一行给出字符串A,长度(A)<= 10,第二行给出字符串B,长度(B)<= 1000.并保证B总是比A.更长
输出描述:
对于每种情况,输出一行包含一个整数,表示B作为A的子串出现的次数。

代码如下:

 #include<iostream>
 #include<string>
 using namespace std;
 int main()
 {
     int N;
     int t =0,i=0;	//t为计数器
     string s,a,b;
     cin>>N;
     while(N--) {
         cin>>a>>b;
         while((i=b.find(a,i))!=(string::npos)) {//见注释
             t++;
             i++;
         }
         cout<<t<<endl;
    }
    return 0;
 }

补充如下:

① i=b.find(a,i)

这个意思是,在字符串b中查找字符串a,从字符串b中的第i个元素开始查找,将返回的int型数值重新赋值给i。

Binary String Matching(C++)
例如:
输入
110
0011011
输出
2
也就是说,如果b字符串里面包含a字符串,则输出字符串a的第一个元素的下标

Binary String Matching(C++)
若字符串b里面没有a这个字符串,则返回-1。

该函数在本程序算法中的作用在于:以次将字符串a从字符串b里面查找,若从字符串b里面找到字符串a,则返回字符串a的第一个字符的下标,接着从字符串b里面找。

②string::npos

string::npos 这个特殊值,说明查找没有匹配。
string::npos 就是一个长度参数,表示直到字符串的结束
string 类将 npos 定义为保证大于任何有效下标的值
string::npos是string容器的一种属性

整体来讲就是说
i=b.find(a,i))!=(string::npos)

这行代码的意思就是:从字符串b里面查找字符串a,若找到返回字符串a的第一个字符在字符串b里面的下标,直到字符串的结束为止。