C ++程序实现短文本大小的字符串搜索算法
在此C++程序中,给出了文本和模式作为输入。作为输出,在文本中搜索模式,并给出该模式的所有实例。
算法
Begin Take the string and pattern as input. Declare the original and duplicate array with their size. Put the lengths of original and duplicate in len_ori and len_dupli. Make a loop for find out the position of the searched pattern. If pattern is not found, print not found otherwise print the no of instances of the searched pattern. End
范例程式码
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char ori[120], dupli[120];
int i, j, k = 0, len_ori, len_dupli;
cout<<"enter string without any blank space"<<endl;
cout<<"\nEnter Original String:";
cin>>ori;
cout<<"输入要搜索的模式:";
cin>>dupli;
len_ori = strlen(ori);
len_dupli = strlen(dupli);
for (i = 0; i <= (len_ori - len_dupli); i++) // loop to find out the position Of searched pattern {
for (j = 0; j < len_dupli; j++) {
if (ori[i + j] != dupli[j])
break ;
}
if (j == len_dupli) {
k++;
cout<<"\nPattern Found at Position: "<<i;
}
}
if (k == 0)
cout<<"\nNo Match Found!";
else
cout<<"\nTotal Instances Found = "<<k;
return 0;
}输出结果
enter string without any blank space Enter Original String:输入要搜索的模式: Pattern Found at Position: 0 Pattern Found at Position: 1 Pattern Found at Position: 2 Pattern Found at Position: 3 Total Instances Found = 4
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便