strstr找出全文所有相同字符串
时间: 2023-06-29 09:11:34 浏览: 44
好的,我可以帮你解决这个问题。你可以使用 C++ STL 中的 std::string 类型和 std::string 类型的成员函数 find 和 substr 来找出全文中所有相同的子字符串。具体实现可以参考下面的代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string text = "hello world, world is beautiful";
std::string target = "world";
std::size_t pos = 0;
while ((pos = text.find(target, pos)) != std::string::npos) {
std::cout << "Found at position " << pos << ": " << text.substr(pos, target.length()) << std::endl;
pos += target.length();
}
return 0;
}
```
在这个例子中,我们定义了一个字符串 `text`,并在其中寻找所有出现的子字符串 `target`。我们使用 `std::string::find` 函数来寻找第一个出现位置,然后用一个 `while` 循环来不断寻找下一个出现位置,直到找不到为止。每次找到一个出现位置,我们都使用 `std::string::substr` 函数来截取出来子字符串,并输出位置和字符串内容。
注意,在使用 `std::string::find` 函数时,我们还要传入一个起始位置参数 `pos`,以便可以从上一次找到的位置的下一个位置开始继续寻找。如果没有找到,`std::string::find` 函数会返回一个特殊的值 `std::string::npos`,表示没有找到。