下面我有一段比较两个字符串的代码。
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);
}
}
旁注:不要使用 long
和 short
作为字符串名称,因为它们是 C++ 保留关键字。
关于c++ - 在另一个字符串中查找字符串的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204358/