实验11-1-8 查找子串 (20 分)
1. 题目摘自
https://pintia.cn/problem-sets/13/problems/593
2. 题目内容
本题要求实现一个字符串查找的简单函数。
函数接口定义:
char *search( char *s, char *t );
函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。
输入样例1:
The C Programming Language
ram
输出样例1:
10
输入样例2:
The C Programming Language
bored
输出样例2:
-1
3. 源码参考
#include <iostream>
using namespace std;
#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 )
{
cout << pos - s << endl;
}
else
{
cout << "-1" << endl;
}
return 0;
}
char *search(char *s, char *t)
{
char *p = NULL, *q = NULL;
int iSucc;
iSucc = 0;
while(*s != '\0')
{
while((*s != '\0') && (*t != '\0') && (*s != *t))
{
s++;
}
if(*s == '\0')
{
break;
}
p = s;
q = t;
while((*p != '\0') && (*q != '\0') && (*p == *q))
{
p++;
q++;
}
if(*q == '\0')
{
iSucc = 1;
break;
}
s++;
}
if(iSucc != 1)
{
return NULL;
}
return s;
}
void ReadString( char s[] )
{
cin.getline(s, MAXS, '\n');
return;
}
网友评论