采用顺序结构存储串,编写一个函数index(s1,s2),用于s2是否是s1的子串。若是,返回其在主串中的位置;否则返回-1

采用顺序结构存储串,编写一个函数index(s1,s2),用于s2是否是s1的子串。若是,返回其在主串中的位置;否则返回-1

从第一个字符开始,取s2长度的子串,与s2进行比较

#include <stdio.h>
int index(char *s1,char *s2)
{
     int i=0,j=0;
    while(s1[i] != '\0')
    {
        j=0;
        while(s1[i+j] != '\0' && s2[j] != '\0')
        {
             if(s1[i+j] != s2[j])
                  break;
             j++;
        }
        if(s2[j] == '\0')
            return i;
        i++;
    }
    return -1;
}
int main()
{
    char s1[1000],s2[100];
    gets(s1);
    gets(s2);
    int idx = index(s1,s2);
    if(idx == -1)
        printf("不是子串");
    else
        printf("是子串");  
}

以下是使用 C 语言实现的函数 index(),用于判断一个串是否为另一个串的子串。该函数采用顺序结构存储串。

#include <stdio.h>
#include <string.h>

int index(char* s1, char* s2) {
    int i, j, k;
    int len1 = strlen(s1);
    int len2 = strlen(s2);

    for (i = 0; i <= len1 - len2; i++) {
        k = i;

        /* 比较s1中以k为起始位置的子串是否和s2匹配 */
        for (j = 0; j < len2; j++) {
            if (s1[k] == s2[j]) {
                k++;
            } else {
                break;
            }
        }

        /* 如果s2是s1的子串,则返回其在s1中的位置 */
        if (j == len2) {
            return i;
        }
    }

    /* 如果s2不是s1的子串,则返回-1 */
    return -1;
}

int main() {
    char s1[] = "hello, world!";
    char s2[] = "world";
    
    int pos = index(s1, s2);
    if (pos == -1) {
        printf("'%s' is not a substring of '%s'\n", s2, s1);
    } else {
        printf("'%s' is a substring of '%s', position: %d\n", s2, s1, pos);
    }

    return 0;
}

该函数通过两个指针依次比较两个字符串中的每个字符,如果在所有字符都匹配的情况下,子串的长度等于目标字符串的位置,则说明子串存在于目标字符串中。

你可以将该函数复制到你的 C 语言项目中,并调用 index() 函数来测试,例如:

int main() {
    char s1[] = "hello, world!";
    char s2[] = "world";
    
    int pos = index(s1, s2);
    if (pos == -1) {
        printf("'%s' is not a substring of '%s'\n", s2, s1);
    } else {
        printf("'%s' is a substring of '%s', position: %d\n", s2, s1, pos);
    }

    return 0;
}

这个例子会输出 world is a substring of hello, world!, position: 7
如果解决了你的问题,请采纳,感激不尽~