下面是用 C++ 实现朴素字符串匹配算法的示例代码:

#include <iostream>
#include <string>

using namespace std;

int naiveStringMatch(const string& text, const string& pattern) {
    int n = text.length();
    int m = pattern.length();

    for (int i = 0; i <= n - m; i++) {
        int j;
        for (j = 0; j < m; j++) {
            if (text[i + j] != pattern[j])
                break;
        }
        if (j == m)
            return i;  // 匹配成功,返回起始位置
    }
    return -1;  // 匹配失败,返回-1
}

int main() {
    string text = "Hello, world!";
    string pattern = "world";

    int result = naiveStringMatch(text, pattern);

    if (result != -1)
        cout << "Pattern found at index " << result << endl;
    else
        cout << "Pattern not found" << endl;

    return 0;
}

在这个例子中,naiveStringMatch 函数接收两个字符串作为参数:text 表示待搜索的文本,pattern 表示待匹配的模式。函数返回匹配成功的起始位置(索引),如果没有匹配则返回 -1。

main 函数中,我们使用示例字符串进行测试。如果模式在文本中匹配成功,将输出模式的起始位置;否则输出 'Pattern not found'。

请注意,朴素字符串匹配算法的时间复杂度为 O((n-m+1) * m),其中 n 是文本长度,m 是模式长度。该算法在最坏情况下的效率相对较低,可以考虑其他更高效的字符串匹配算法,如 KMP 算法或 Boyer-Moore 算法。

C++ 实现朴素字符串匹配算法

原文地址: https://www.cveoy.top/t/topic/co87 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录