温馨提示×

C++ strstr函数能否自定义

c++
小樊
82
2024-06-13 18:21:43
栏目: 编程语言

在C++中,strstr函数是用来在一个字符串中查找子字符串的函数,它是标准库函数,无法自定义。不过,我们可以编写自己的字符串查找函数来实现类似的功能,例如可以使用循环遍历字符串来进行匹配。以下是一个简单的自定义字符串查找函数示例:

#include <iostream>

int custom_strstr(const char* haystack, const char* needle) {
    int haystack_len = strlen(haystack);
    int needle_len = strlen(needle);

    for (int i = 0; i <= haystack_len - needle_len; i++) {
        int j;
        for (j = 0; j < needle_len; j++) {
            if (haystack[i + j] != needle[j]) {
                break;
            }
        }
        if (j == needle_len) {
            return i;
        }
    }

    return -1;
}

int main() {
    const char* haystack = "hello world";
    const char* needle = "world";

    int index = custom_strstr(haystack, needle);

    if (index != -1) {
        std::cout << "Found at index " << index << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

这段代码定义了一个custom_strstr函数,用来在字符串haystack中查找子字符串needle,并返回第一次出现的位置索引。在main函数中使用这个自定义函数来查找子字符串"world"在字符串"hello world"中的位置。

0