本题要求:
实现一个字符串查找的简单函数。
函数接口定义:
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)
{
char *p=NULL,*q,*k;
while(*s){
q=s;
k=t;
while(*k){
if(*q==*k){
q++;
k++;
}
else break;
}
if('\0'==*k)return s;//我原本写的是p=s,不知道为啥有一个测试点不通过
else
s++;
}
return NULL;
}
欢迎讨论

这篇博客主要介绍如何用C语言编写一个简单的函数,该函数用于在字符串中查找子串,并返回子串的首地址。如果未找到子串,则返回NULL。文章提供了函数接口定义和裁判测试程序的样例。
3300

被折叠的 条评论
为什么被折叠?



