请编写一个函数 int find(char s[],char t[]), 该函数在字符串s中查找字符串t,如果找到,则返回字符串t在字符串s中的位置(整数值):否则返回-1。本题要求:用数组方式及两重循环来实现该函数。
注意:部分源程序已存在考生文件夹的文件PROC1.cpp中。
请勿修改主函数和其他函数中的任何内容,仅在函数find()的花括号中填写若干语句。
文件PROC1.cpp的内容如下:
//PROC1.cpp
#include<iostream>
using namespace std;
int find(char s[],char t[]);
const int MAXLINE = 256;
int main()
char source[MAXLINE],target[MAXLINE];
cout<<"Please input a string for searching:\n";
cin.getline(source,MAXLINE);
cout<<"Please input a string you want to find:\n";
cin.getline(target,MAXLINE);
int intPos=find(source,target);
if(intPos>=0)
cout<<"Finding it,The target string is at index"
<<intPos<<"of the source string\n";
else
cout<<"Not finding it \n";
return 0;
int find(char s[],char t[])
//********
参考答案:
int find(char s[ ],char t[ ])
{
int i=0, j=0;
for( i=0;s[i] !=’\0’;i++)
{
if(t [0]==s[i])
{
while(t [j] !=’\0’&&s [i+j]!=’\0’)
{
j++;
if(t [j] !=s[i+j])
break;
}
}
if(t[j]==’\0’)
return i;
}
return -A;
}
解析:
本题是一道简单应用题。函数int find(char s[],char t[]的功能是在字符串s中查找字符串t,如果找到,则返回字符串t在字符串s中的位置(整数值);否则返回 -1,而且用数组方式及两重循环来实现该函数。