C++ 查找给定字符串中所有子字符串的出现次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22315738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find occurrences of all substrings in a given string
提问by Sparrow
I use a simple string function strstr
to find the first occurrence of a sting in a text. I use following code to count the number of unique words in a text.
我使用一个简单的字符串函数strstr
来查找文本中第一次出现的字符串。我使用以下代码来计算文本中唯一单词的数量。
for(int i=0;i<24;i++)
{
if(strstr(text,ops[i]))
{
op++;
}
}
But I want to find the occurrence of all the sub strings in the program. I could do that easily in JAVA. But I am asked to do this in C++. Any help?
但是我想找到程序中所有子字符串的出现。我可以在 JAVA 中轻松做到这一点。但我被要求在 C++ 中做到这一点。有什么帮助吗?
回答by jfly
strstr()
is for the C-style string, if you are really using C++, std::string
and its member function would be much more convenient.
strstr()
是针对C风格的字符串,如果你真的用C++的话,std::string
它的成员函数会方便很多。
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s("hello hello");
int count = 0;
size_t nPos = s.find("hello", 0); // first occurrence
while(nPos != string::npos)
{
count++;
nPos = s.find("hello", nPos + 1);
}
cout << count;
};
回答by acarlon
You can use one of the std::string find methods which would be easier (and safer), but if you really need to use strstr:
您可以使用 std::string 查找方法之一,这会更容易(也更安全),但如果您确实需要使用 strstr:
int _tmain(int argc, _TCHAR* argv[])
{
const char test[] = "this test is a test";
const char subStr[] = "test";
const char* pCurrent = strstr( test, subStr );
while( pCurrent != NULL )
{
std::cout << "found" << std::endl;
pCurrent++;
pCurrent = strstr( pCurrent, subStr );
}
return 0;
}
This just increments the point where the last sub string was found. Note that you should do the normal string length, NULL and safety checks.
这只会增加找到最后一个子字符串的点。请注意,您应该进行正常的字符串长度、NULL 和安全检查。