gpt4 book ai didi

c++ - 在另一个字符串中查找字符串的所有实例

转载 作者:行者123 更新时间:2023-11-30 05:43:28 25 4
gpt4 key购买 nike

下面我有一段比较两个字符串的代码。

if (long.find(short) != string::npos) {
cout << "FOUND";
}

这只会告诉我它是否在长字符串中找到了短字符串。但是我怎样才能找到所有的实例并告诉用户字符串的这些实例显示在哪里呢?

我想也许可以将其设为一个循环,但我在实现它时遇到了麻烦。

最佳答案

你可以做类似的事情

#include <iostream>
#include <string>

int main()
{
std::string test = "we are searching for searching here";
std::string str = "searching";
std::string::size_type start = test.find(str); // find the first instance
while(start != std::string::npos) // repeat for the rest
{
std::cout << "Found on pos: " << start << std::endl;
start = test.find(str, start + 1);
}
}

旁注:不要使用 longshort 作为字符串名称,因为它们是 C++ 保留关键字。

关于c++ - 在另一个字符串中查找字符串的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com