繁体   English   中英

查找给定字符串中所有子字符串的出现次数

[英]Find occurrences of all substrings in a given string

我使用一个简单的字符串函数strstr来查找某个字符串中第一次出现的字符串。 我使用以下代码来计算文本中唯一单词的数量。

for (int i = 0; i < 24; i++) 
{
    if (strstr(text, ops[i])) 
    {
        op++;
    }
}

但是我想找到程序中所有子字符串的出现。 我怎样才能做到这一点?

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;
};

您可以使用 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;
}

这只会增加找到最后一个子字符串的点。 请注意,您应该进行正常的字符串长度、NULL 和安全检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM