代码改变世界

查询字符串在指定字符串中出现的次数

2009-10-09 11:12  Iron  阅读(820)  评论(0编辑  收藏  举报

思路:遍历指定字符串,找到和字符串有相同开始的位置,然后逐个比对,比对完成后,接着对指定字符串做查找操作

#include <cstdio>
#include <cstring>
int CountOfsubstr(const char* src,char* substr)
{
 int count = 0;
 const char* s = src;
 int len = strlen(src);
 for(int i=0; i<len; i++)
 {
  if (*s==*substr)
  {
   int j;
   int substrLen = strlen(substr);
   for (j=0; j<substrLen;j++)
   {
    if (*(s+j)==*(substr+j))
    {
    }
    else
    {
     break;
    }
   }
   if (strlen(substr) == j)
   {
    count++;
   }
  }
  s++;
 }
 return count;
}
int main()
{
 printf("%d\n",CountOfsubstr("abcacbabcabc","abc"));
 return 1;
}