从主串S的第1个字符起和子串的第一个字符比较之,若相等,则继续逐个比较后续字符,否则从主串的下一个字符起再重新和模式的字符比较之。依次类推,直至子串T中的每个字符依次和主串S中的一个连续的字符序列相等,则称匹配成功,函数值为和子串T中第一个字符相等的字符在主串中的序号,否则称匹配不成功,函数值为零。
你的任务是将S中每次比较的字符输出来,并将匹配的序号输出。
输入描述
3组字符串,每组字符串占一行。每行包含由空格分隔的两个字符串,字符串仅由英文小写字母组成且长度不大于100。3组字符串,每组字符串占一行。每行包含由空格分隔的两个字符串,字符串仅由英文小写字母组成且长度不大于100。
输出描述
每组数据输出2行,第一行是S中每次比较的字符,第二行是后一个字符串在前一个字符串中的位置,如果不匹配,则输出0。
样例输入:
string str
thisisalongstring isa
nosubstring subt
样例输出:
str
1
thisisisa
5
nosubsubsttring
0
因为刚开始学编程,写的代码并不那么简洁,但是应该有很大优化空间,不过这个题已经花了我不少时间,所以没有再作优化,但是稍稍看看思路也是可以的嘛。
代码如下:
#include<stdio.h> #include<string.h> char not1[100],not2[100],not3[100]; int j1,j2,j3; int compare1(char S[100],char T[100]) { int i,j; int m=1; unsigned long long int n,n1; i=0; j=0; n=strlen(T); /*Thisisanostring*/ n1=strlen(S); /*isa*/ for(;j<n&&i<n1;) { if(S[i]==T[j]) /*apple*/ { /*ppc*/ i++; j++; } else { i=i-j+1; j=0; } not1[0]=S[0]; not1[m]=S[i]; m++; } if(j==n) { return i-n+1; } else { return 0; } } int compare2(char S[100],char T[100]) { int i,j; int m=1; unsigned long long int n,n1; i=0; j=0; n=strlen(T); /*Thisisanostring*/ n1=strlen(S); /*isa*/ for(;j<n&&i<n1;) { if(S[i]==T[j]) /*apple*/ { /*ppc*/ i++; j++; } else { i=i-j+1; j=0; } not2[0]=S[0]; not2[m]=S[i]; m++; } if(j==n) { return i-n+1; } else { return 0; } } int compare3(char S[100],char T[100]) { int i,j; int m=1; unsigned long long int n,n1; i=0; j=0; n=strlen(T); /*Thisisanostring*/ n1=strlen(S); /*isa*/ for(;j<n&&i<n1;) { if(S[i]==T[j]) /*apple*/ { /*ppc*/ i++; j++; } else { i=i-j+1; j=0; } not3[0]=S[0]; not3[m]=S[i]; m++; } if(j==n) { return i-n+1; } else { return 0; } } int main() { unsigned long long int k1,k2,k3; char S[100]; char T[100]; char S1[100]; char T1[100]; char S2[100]; char T2[100]; scanf("%s",S); scanf("%s",T); scanf("%s",S1); scanf("%s",T1); scanf("%s",S2); scanf("%s",T2); int a,b,c; a=compare1(S,T); if(a!=0) { j1=strlen(not1); not1[j1-1]='\0'; printf("%s",not1); printf("\n"); printf("%d\n",a); } else { printf("%s\n",not1); printf("0\n"); } b=compare2(S1,T1); if(b!=0) { j2=strlen(not2); not2[j2-1]='\0'; printf("%s",not2); printf("\n"); printf("%d\n",b); } else { printf("%s\n",not2); printf("0\n"); } c=compare3(S2,T2); if(c!=0) { j3=strlen(not3); not3[j3-1]='\0'; printf("%s",not3); printf("\n"); printf("%d\n",c); } else { printf("%s\n",not3); printf("0\n"); } return 0; }