c语言

字符串查找函数c语言怎么实现

小亿
85
2024-08-05 17:50:10
栏目: 编程语言

在C语言中,可以通过自己编写一个字符串查找函数来实现字符串查找的功能。下面是一个简单的示例代码:

#include <stdio.h>

int findString(char *str, char *substr) {
    int i, j, k;

    for (i = 0; str[i] != '\0'; i++) {
        j = 0;
        k = i;

        while (str[k] == substr[j] && substr[j] != '\0') {
            k++;
            j++;
        }

        if (substr[j] == '\0') {
            return i;
        }
    }

    return -1;
}

int main() {
    char str[] = "Hello, world!";
    char substr[] = "world";

    int index = findString(str, substr);

    if (index != -1) {
        printf("Substring found at index: %d\n", index);
    } else {
        printf("Substring not found\n");
    }

    return 0;
}

在上面的示例代码中,findString函数接受两个参数:str为要查找的字符串,substr为要查找的子字符串。函数会返回子字符串在原字符串中的起始索引,如果找不到则返回-1。在main函数中,我们可以调用findString函数来查找指定的子字符串在原字符串中的位置。

0
看了该问题的人还看了