习题11-6 查找子串(20 分)
本题要求实现一个字符串查找的简单函数。
函数接口定义:
1
| char *search( char *s, char *t );
|
函数search
在字符串s
中查找子串t
,返回子串t在s
中的首地址。若未找到,则返回NULL。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <stdio.h> #define MAXS 30
char *search(char *s, char *t); void ReadString( char s[] );
int main() { char s[MAXS], t[MAXS], *pos;
ReadString(s); ReadString(t); pos = search(s, t); if ( pos != NULL ) printf("%d\n", pos - s); else printf("-1\n");
return 0; }
|
输入样例1:
1 2
| The C Programming Language ram
|
输出样例1:
输入样例2:
1 2
| The C Programming Language bored
|
输出样例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <stdio.h> #define MAXS 30
char *search(char *s, char *t); void ReadString( char s[] );
int main() { char s[MAXS], t[MAXS], *pos;
ReadString(s); ReadString(t); pos = search(s, t); if ( pos != NULL ) printf("%d\n", pos - s); else printf("-1\n");
return 0; } void ReadString(char s[]){ gets(s); } char *search(char *s, char *t) { int i, j, sLen, tLen; for (i=0; s[i]!='\0'; i++); sLen=i; for (j=0; t[j]!='\0'; j++); tLen=j; i=j=0; while (i < sLen && j < tLen) { if (s[i] == t[j]) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j == tLen) return &s[i - j]; else return NULL; }
|