c语言

C语言search函数的高级应用案例

小樊
82
2024-08-06 18:32:15
栏目: 编程语言

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

// Function to search for a substring in a given string
int search(char *str, char *substr) {
    int i, j, start, found;

    for (i = 0; str[i] != '\0'; i++) {
        start = i;
        found = 1;

        for (j = 0; substr[j] != '\0'; j++) {
            if (str[start] != substr[j]) {
                found = 0;
                break;
            }
            start++;
        }

        if (found) {
            return i;
        }
    }

    return -1;
}

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

    int index = search(str, substr);

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

    return 0;
}

这是一个简单的C语言程序,演示了如何使用search函数来在一个字符串中搜索一个子字符串。在这个例子中,我们定义了一个search函数,它接受两个参数:一个字符串和一个子字符串,并返回子字符串在字符串中第一次出现的位置。在main函数中,我们使用这个search函数来搜索字符串"Hello, world!“中的子字符串"world”。如果子字符串存在,则打印它在字符串中的位置;否则打印"Substring not found"。运行程序后,输出结果应该是"Substring found at index 7"。

0
看了该问题的人还看了