登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

5.9-12  

2006-03-28 00:16:36|  分类: C/C++ |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

//问题描述:  Write a function that counts the number of occurrences
// of a pair of letters in a string and another that does the same
// in a zero-terminated array of char (a C-style string). For
// example, the pair "ab" appears twice in "xabaacbaxabb".
//备注:     
//作者:      杨明哲
//完成日期:  2005-03-25
//BUG报告;  dearymz@163.com

#include <cassert>
#include <iostream>
using namespace std;


namespace ymz
{
 //统计pSource中pAB的前两个字符出现的次数
 int abCount(const char* pSource, const char* pAB)
 {
  assert(pAB != NULL && pSource != NULL && strlen(pAB) >= 2);//对输入合法的检测
  int counter = 0;
  char c;
  bool firstMatch = false;
  for(int i = 0; ; i++)
  {
   c = pSource[i];
   if(c == '\0')
    break;
   if(firstMatch)//准备匹配第二个字符
   {
    if(c == pAB[1])
    {
     counter ++;
    }
    firstMatch = false;
   }
   else//匹配第一个字符
   {
    if(c == pAB[0])
    {
     firstMatch = true;
    }
   }
  }
  return counter;
 }
 //统计pSource中pAB的前两个字符出现的次数
 //    当然这里也可以构建全新的函数。但“重用”以前的代码也是一种好的选择。
 //         这样做可以给用户提供全新的操作界面,而减小核心的开发量。
 int abCount(const string& source, const string& ab)
 {
  assert(ab.length() >= 2);//对输入合法的检测
  return abCount(source.c_str(), ab.c_str());
 }
}

//测试函数
void main()
{
 char c_source[] = "xabaacbaxabb";
 char c_ab[] = "ab";
 string s_source = c_source;
 string s_ab = c_ab;
 cout<<"To count \""<<c_ab<<"\" in \""<<c_source<<"\":"<<endl;
 cout<<"Counter by char  : "<<ymz::abCount(c_source, c_ab)<<endl;
 cout<<"Counter by string: "<<ymz::abCount(s_source, s_ab)<<endl;
 cin.get();
}

  评论这张
 
阅读(771)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018