【问题描述】
编写一函数strend(s, t),如果字符串t出现在字符串s的尾部,该函数返回1,否则返回0。要求在main函数中测试该函数:先从键盘输入字符串s、t(不超过100个字符),然后调用该函数,并输出返回的结果。
【输入形式】
从键盘分行输入两个字符串:s,t
【输出形式】
输出有两种可能,Yes或No
【输入样例】
abcdefgh
fgh
【输出样例】
Yes【样例说明】
输入了两个字符串s,t,发现t是在s的尾部,则输出Yes
#include <stdio.h>
#include <string.h>#define MaxSize 100
typedef char ElementType;typedef struct
{int length;ElementType data[MaxSize];
}SString;
int SString_tail(SString s,SString t)
{int tail=s.length-t.length;if(tail<0||t.length==0){return 0;}int i;for ( i = 0; i <t.length ; i++) {if(s.data[tail++]!=t.data[i]){return 0;}}return 1;
}
void PrintSString(SString L)
{int i;for ( i = 0; i < L.length; i++) {printf("%3c",L.data[i]);}printf("\n");
}int main() {SString s,t;fgets(s.data,100,stdin);fgets(t.data,100,stdin);s.length=strlen(s.data);t.length=strlen(t.data);
// PrintSString(s);
// PrintSString(t);int ret;ret=SString_tail(s,t);if(ret){printf("Yes");} else{printf("No");}return 0;
}
【问题描述】用简单模式匹配算法判断模式串T是否在主串S的一个给定位置(pos)开始的串中,若在,则输出模式串在主串的第pos位置开始的匹配位置,否则,匹配失败,返回零值。
【输入形式】主串S,模式串T,起始位置pos
【输出形式】匹配的相关信息
【样例输入1】Please input the Main SString S:aabaabaabaac
Please input the other SString T:aabaac
the start position:5
【样例输出1】
the index result is:
The postion of T in the Main SString S from 5 chars on is: 7
【样例输入2】
Please input the Main SString S:aabaabaabaac
Please input the other SString T:aabaac
the start position:8
#include <stdio.h>
#include <string.h>
int Index(char S[],char T[],int pos)
{int i=0,j=pos-1;int ls=strlen(S)-1,lt=strlen(T)-1;if(lt>ls||lt==0||ls==0){return 0;}while (i<=lt&&j<=ls){if(S[j]==T[i]){i++,j++;if(i==lt){return j-lt+1;}} else{j=j-i+1;i=0;}}return 0;
}
int main() {char S[100], T[100];int pos;printf("Please input the Main SString S:");fgets(S,100,stdin);printf("Please input the other SString T:");fgets(T,100,stdin);printf("the start position:");scanf("%d", &pos);int ret = Index(S, T, pos);if (ret) {printf("\nthe index result is:\nThe postion of T in the Main SString S from %d chars on is: %d", pos, ret);} else {printf(" \nthe index result is:\nFailure to Index the SString!");}return 0;}