MST

星途 面试题库

面试题:C++中利用find实现模糊查找的基本思路

请描述在C++中,如何基于STL算法`find`实现一个简单的模糊查找方案,例如查找字符串中包含某特定子串的位置。假设字符串为`std::string`类型,简要说明实现的步骤和可能用到的辅助函数或操作。
25.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 步骤一:准备字符串:有两个std::string,一个是待查找的主字符串haystack,另一个是要查找的子字符串needle
    • 步骤二:使用std::search(基于find思想的扩展查找算法)std::search可以在一个范围内查找另一个子范围。它的函数原型为ForwardIt1 search(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2, ForwardIt2 last2);。在std::string的场景下,ForwardIt1ForwardIt2就是std::string::iterator。我们可以传入haystack.begin()haystack.end()作为主字符串范围,needle.begin()needle.end()作为子字符串范围。
    • 步骤三:处理结果:如果找到了,std::search会返回一个指向主字符串中找到子字符串起始位置的迭代器。可以通过这个迭代器计算出子字符串在主字符串中的位置(例如通过std::distance(haystack.begin(), result)得到位置索引)。如果没找到,std::search会返回haystack.end()
  2. 可能用到的辅助函数或操作
    • std::distance:用于计算两个迭代器之间的距离,在得到找到子字符串的迭代器后,通过它可以计算出子字符串在主字符串中的位置索引。例如:
#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string haystack = "hello world";
    std::string needle = "world";
    auto result = std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end());
    if (result != haystack.end()) {
        auto position = std::distance(haystack.begin(), result);
        std::cout << "Substring found at position: " << position << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }
    return 0;
}

这里通过std::distance计算出子字符串"world""hello world"中的位置。