我的代码:
#include <string>
using std::string;
int CountMatch(string MatchStr, string s)
{
int pos = 0;
int tpos = 0;
int count = 0;
while ((tpos = s.find(MatchStr, pos)) != string::npos)
{
count++;
pos = tpos + MatchStr.length();
}
return count;
}
int CountCharStringMatch(char MatchStr[], char s[])
{
char* spos = NULL;
int tpos = 0;
int count = 0;
while ((spos = strstr(s + tpos, MatchStr)) != NULL)
{
count++;
tpos = spos - s + strlen(MatchStr);
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
string s = "nihao,john.oh john";
string MatchString = "john";
int count = CountMatch(MatchString, s);
char as[] = "nihao,john.oh john";
char mas[] = "john";
int acount = CountCharStringMatch(mas, as);
return 0;
}
下面是书上的答案:
size_t count_charpair(string const & s, char a, char b)
{
size_t result = 0;
string::const_iterator p = s.begin();
while (p != s.end())
{
if (*p++ == a)
{
if (p != s.end() && *p == b)
{
++result;
}
}
}
return result;
}
size_t count_charpair(char const *s, char a, char b)
{
assert(s);
size_t result = 0;
while (*s)
{
if (*s++ == a)
{
if (*s == b)
{
++result;
}
}
}
return result;
}
对比得:
1.我的代码中参数缺少const,从而有可能使其在函数中被修改。
2.我使用了标准库,而答案则尽量使用原始数据指针。可能会提高代码执行效率。
3.我的代码中没有考虑在"aaaa"中查找"aa"的次数,应该是3次的情况。
4.其函数参数使用了引用,而我的函数参数是直接的形参,可能导致参数复制。
因此,我的改进版:
int CountMatch(const string & MatchStr,const string &s)
{
int pos = 0;
int tpos = 0;
int count = 0;
while ((tpos = s.find(MatchStr, pos)) != string::npos)
{
count++;
pos = tpos + 1;
}
return count;
}
int CountCharStringMatch(const char MatchStr[],const char s[])
{
const char* spos = NULL;
int tpos = 0;
int count = 0;
while ((spos = strstr(s + tpos, MatchStr)) != NULL)
{
count++;
tpos = spos - s + 1;
}
return count;
}