首页 > 试题广场 >

编写函数 int index(char *s, char *

[问答题]

编写函数 int index(char *s char *t),返回字符串 t 在字符串 s 中出现的最左边的位置,如果在 s 中没有与 t 匹配的子串,就返回-1

推荐

解:

源程序:

#include <iostream.h>
int index( char *s, char *t)
{
int i,j,k;
for(i = 0; s[i] != '\0'; i++)
{
for(j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
;
if (t[k] =='\0')
return i;
}
return -1;
}
void main()
{
int n;
char str1[20],str2[20];
cout << "输入一个英语单词:";
cin >> str1;
cout << "输入另一个英语单词:";
cin >> str2;
n = index(str1,str2);
if (n > 0)
cout << str2 << "在" << str1 << "中左起第" << n+1
<< "个位置。"<<endl;
else
cout << str2 << "不在" << str1 << "中。" << endl;
}

程序运行输出:

输入一个英语单词:abcdefgh

输入另一个英语单词:de

de abcdefghijk 中左起第 4 个位置。



发表于 2018-04-18 20:45:21 回复(0)