C++程序设计语言练习5.12 对比string和C字符串的优劣

我的代码:

#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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值