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