//问题描述: 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();
}
评论