方法一
#include<iostream>
#include<string.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
int main(){
//a[20]主串 b[20]子串
char a[20],b[20];
cin>>a>>b;
int i=0,j=0;
while(a[i]!='\0'&&b[j]!='\0'){
if(a[i]==b[j]){
i++;
j++;
}else{
i=i-j+1;
j=0;
}
}
if(b[j]=='\0'){
cout<<"在主串的第"<<i-j+1<<"个位置匹配成功"<<endl;
}else{
cout<<"未找到相关子串"<<endl;
}
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
double time;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nBeginTime);
for (int i = 0; i < 1000; i++)
{
i++;
}
QueryPerformanceCounter(&nEndTime);
time=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)*1000000000/(double)(nFreq.QuadPart);
cout<<"程序运行时间(单位是纳秒):"<<time<<endl;
return 0;
}
方法二
#include<iostream>
#include<string.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
int main(){
//a[20]主串 b[20]子串
char a[20],b[20];
cin>>a>>b;
int i=0,j=0,index=0;
while(a[i]!='\0'&&b[j]!='\0'){
if(a[i]==b[j]){
i++;
j++;
}else{
index++;
i=index;
j=0;
}
}
if(b[j]=='\0'){
cout<<"在主串的第"<<i-j+1<<"个位置匹配成功"<<endl;
}else{
cout<<"未找到相关子串"<<endl;
}
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
double time;
QueryPerformanceFrequency(&nFreq);
QueryPerformanceCounter(&nBeginTime);
for (int i = 0; i < 1000; i++)
{
i++;
}
QueryPerformanceCounter(&nEndTime);
time=(double)(nEndTime.QuadPart-nBeginTime.QuadPart)*1000000000/(double)(nFreq.QuadPart);
cout<<"程序运行时间(单位是纳秒):"<<time<<endl;
return 0;
}