本题要求实现一个字符串查找的简单函数。
函数接口定义:
char *search( char *s, char *t );
函数search
在字符串s
中查找子串t
,返回子串t在s
中的首地址。若未找到,则返回NULL。
裁判测试程序样例:
#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:
The C Programming Language
ram
输出样例1:
10
输入样例2:
The C Programming Language
bored
输出样例2:
-1
个人答案(仅供参考):
char *search( char *s, char *t )
{
return strstr(s,t);
}
/*
char * strstr(char* str1, char * str2); 功能:找出字符串str2在str1字符串中第一次出现的
位置(不包括str2字符串的结束符),返回该位置的指针,若找不到则返回空指针
*/
char * search( char *s, char *t )
{
int i, n = strlen(t), m = strlen(s);
while(*s)
{
i = 0;
while(*(s+i) == *(t+i) && *(t+i))
i++;
if(i == n)
return s;
else
*s++;
}
return NULL;
}
/*
例如:当s为:fffffabc,t为abc。代码中 while(*(s+i) == *(t+i) && *(t+i)) 如果缺少 *
(t+i)! = '\0’这个条件,致使当循环到字串t的结尾时,* (t+i) 为 ‘\0’ ,而 * (s+i) 也为 ‘\0’ ,
它们刚好相等,那么 i 就自加为4,这样 i 不等于strlen(t),返回不了t在s中的首地址。
*/