采用顺序结构存储串,编写一个函数index(s1,s2),用于判断s2是否是s1的子串。若是,则返回其在主串中的位置,否则返回-1。
时间: 2024-05-09 12:20:54 浏览: 11
以下是Python实现:
```python
def index(s1, s2):
n = len(s1)
m = len(s2)
for i in range(n-m+1):
j = 0
while j < m and s1[i+j] == s2[j]:
j += 1
if j == m:
return i
return -1
```
其中,n和m分别为主串和子串的长度。通过循环遍历主串中每一个可能的起始位置,并在每个位置上逐个比较子串中的字符和主串中对应位置的字符是否相等,直到找到子串完全匹配主串的一段位置,或者遍历完所有可能的位置都没有找到匹配的子串。如果找到匹配的子串,则返回其在主串中的起始位置。如果遍历完所有可能的位置都没有找到匹配的子串,则返回-1表示未找到。
相关问题
采用顺序结构存储串,用c语言编写一个函数index(s1,s2),用于判断s2是否是s1的子串。若是,则返回其在主串中的位置,否则返回-1。
```
#include <stdio.h>
int index(char s1[], char s2[]) {
int i = 0, j = 0, k = -1;
while (s1[i] != '\0' && s2[j] != '\0') {
if (s1[i] == s2[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (s2[j] == '\0') {
k = i - j;
}
return k;
}
int main() {
char s1[] = "hello, world!";
char s2[] = "world";
int pos = index(s1, s2);
if (pos != -1) {
printf("'%s' is a substring of '%s' at position %d.\n", s2, s1, pos);
} else {
printf("'%s' is not a substring of '%s'.\n", s2, s1);
}
return 0;
}
```
采用顺序结构存储串,编写一个函数index(s1,s2),用于s2是否是s1的子串。若是,返回其在主串的位置;否则返回-1.用c语言编写完整代码
下面是采用顺序结构存储串,编写的函数index(s1,s2)的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100
int index(char *s1, char *s2) {
int i, j, k;
int len1 = strlen(s1), len2 = strlen(s2);
for (i = 0; i < len1 - len2 + 1; i++) {
for (j = i, k = 0; s2[k] != '\0' && s1[j] == s2[k]; j++, k++);
if (k == len2) return i;
}
return -1;
}
int main() {
char s1[MAXLEN], s2[MAXLEN];
printf("请输入主串s1:");
scanf("%s", s1);
printf("请输入子串s2:");
scanf("%s", s2);
int pos = index(s1, s2);
if (pos != -1) {
printf("子串在主串中的位置为:%d\n", pos);
} else {
printf("子串不是主串的子串!\n");
}
return 0;
}
```
该函数的思路是:枚举主串中每一个可能的子串起点,然后逐个字符比较主串和子串对应位置上的字符。如果某个位置上的字符不匹配,就跳出当前循环,开始枚举下一个子串起点。如果子串中的所有字符都能和主串中对应的字符匹配,就说明子串是主串的一个子串,返回子串在主串中的起始位置。如果遍历完所有可能的子串起点后都没有找到子串,就返回-1表示子串不是主串的子串。
以上代码可以通过以下方式编译并运行:
```bash
$ gcc -o main main.c
$ ./main
请输入主串s1:hello world
请输入子串s2:world
子串在主串中的位置为:6
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)