如何在一串序列中寻找子序列(第n次?(语言-c语言)

用c语言编写在一串序列中寻找他的子序列,返回子序列第一个字符的地址,更进一步是,寻找第n次出现的子序列

可以使用 C 库函数 strstr() 来实现在一串序列中寻找子序列,它会返回子序列第一个字符的地址。如果要寻找第 n 次出现的子序列,可以使用一个循环,在每次找到子序列后移动指针并计数,直到找到第 n 次出现的子序列为止。


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

int main() {
    char str[] = "This is a test string";
    char sub[] = "is";
    int n = 2;
    char *p = str;

    for (int i = 0; i < n; i++) {
        p = strstr(p, sub);
        if (p == NULL) {
            printf("Substring not found\n");
            return 0;
        }
        p++;
    }

    printf("The %dth occurrence of '%s' is at position %ld\n", n, sub, p - str - strlen(sub));
    return 0;
}

上面的代码在字符串 "This is a test string" 中寻找第 2 次出现的 "is" 子序列,并打印出它第一个字符在原串中的位置
注意:如果你要处理的字符串非常大,使用底层的指针操作或者KMP算法会更快

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

char *find_subsequence(char *sequence, char *subsequence, int n) {
    char *result = sequence;
    int i;
    for (i = 0; i < n; i++) {
        result = strstr(result, subsequence);
        if (result == NULL) {
            return NULL;
        }
        result++;
    }
    return result - 1;
}

int main() {
    char sequence[] = "hello, world! this is a test sequence";
    char subsequence[] = "is";
    char *result = find_subsequence(sequence, subsequence, 2);
    if (result == NULL) {
        printf("Subsequence not found\n");
    } else {
        printf("Subsequence found at position: %ld\n", result - sequence);
    }
    return 0;
}


```c


```