用C++和C语言分别编写函数int index(chars, chart),字符串t在字符s中出现的最左边的位置作为返回值,如果s中没有与t匹配的子串,就返回-1,然后输出完整的代码
时间: 2024-05-05 12:20:05 浏览: 12
以下是使用C语言编写的函数int index(chars, chart)的代码:
```
#include <stdio.h>
#include <string.h>
int index(char* s, char* t)
{
int i, j, k;
int slen = strlen(s);
int tlen = strlen(t);
for(i = 0; i <= slen - tlen; i++)
{
j = i;
k = 0;
while(k < tlen && s[j] == t[k]) // 匹配t与s的子串
{
j++;
k++;
}
if(k == tlen) // 若匹配成功
return i;
}
return -1; // 若匹配失败
}
int main()
{
char s[100], t[100];
printf("请输入字符s: ");
scanf("%s", s);
printf("请输入字符t: ");
scanf("%s", t);
int pos = index(s, t); // 调用index函数
if(pos == -1)
printf("不存在子串t\n");
else
printf("子串t在字符串s中的位置为%d\n", pos);
return 0;
}
```
以下是使用C++语言编写的函数int index(chars, chart)的代码:
```
#include <iostream>
#include <string>
using namespace std;
int index(string s, string t)
{
int i, j, k;
int slen = s.length();
int tlen = t.length();
for(i = 0; i <= slen - tlen; i++)
{
j = i;
k = 0;
while(k < tlen && s[j] == t[k]) // 匹配t与s的子串
{
j++;
k++;
}
if(k == tlen) // 若匹配成功
return i;
}
return -1; // 若匹配失败
}
int main()
{
string s, t;
cout << "请输入字符s: ";
cin >> s;
cout << "请输入字符t: ";
cin >> t;
int pos = index(s, t); // 调用index函数
if(pos == -1)
cout << "不存在子串t" << endl;
else
cout << "子串t在字符串s中的位置为" << pos << endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)