1. 程式人生 > >C++ 字串中子串個數

C++ 字串中子串個數

子串可重疊情況:

int fun1(const std::string& str, const std::string& sub)
{
	int num = 0;
	for (size_t i = 0; (i = str.find(sub, i)) != std::string::npos; num++, i++);
	return num;
}

子串不可重疊情況:

int fun2(const std::string& str, const std::string& sub)
{
	int num = 0;
	size_t len = sub.length();
	if (len == 0)len=1;//應付空子串呼叫
	for (size_t i=0; (i=str.find(sub,i)) != std::string::npos; num++, i+=len);
	return num;
}