Loading

C++不调用string实现字符串中子串重复次数统计

提要

C++标准库中封装了很好用的string类型,可以轻松通过find查找子串。
这里给出一种纯粹使用char*的子串统计实现

实现

嵌套遍历母串和子串进行逐个比对,核心是计数器自增的时机

#include<iostream>

int match(const char* main,const char* sub)
{
    int count = 0;
    for(int i=0;main[i]!='\0';i++)
    {
        for(int j=0;sub[j]!='\0';j++)
        {
            if(main[i+j]!=sub[j]){break;}
            if(sub[j+1]=='\0'){count++;}  //core
        }        
    }
    return count;
}

int main(int argc, char const *argv[])
{
    char *main="ABCBCDEEEF";
    char *sub="EE";
    std::cout<<match(main,sub)<<std::endl;
    return 0;
}
//result = 2

附加

另附使用C++标准库string的简洁实现

#include<iostream>
#include<string>

int match(const std::string& main,const std::string& sub)
{
    int count = 0;
    int index = 0;
    while((index=main.find(sub,index))<main.length())      
    {
        count++;
        index++;
    }
    return count;
}

int main(int argc, char const *argv[])
{
    std::string main="ABCBCDEEEF";
    std::string sub="EE";
    std::cout<<match(main,sub)<<std::endl;
    return 0;
}
posted @ 2020-12-22 22:28  azureology  阅读(421)  评论(0)    收藏  举报