喵知道:
1、计算文章中有多少个空格(连续空格记作一次);
2、减去文章头部和尾部的空格(如果存在的话);
3、得到所有单词组成的间隔数,间隔+1即为文章单词总数。
源码:
void CHAROPERATE::calculateOfEnglishWord(const char*str, const unsigned int length)
{
/*统计空格个数推导出单词个数*/
unsigned int lastBlankSite = 0;
unsigned int cntOfWord=0;
bool bTIfRepeat = FALSE;
for (unsigned int i = 0; i < length; ++i)
{
if (str[i] == 32 && bTIfRepeat)
{
lastBlankSite = i;
continue;
}
if (str[i] == 32)
{
lastBlankSite = i;
++cntOfWord;
bTIfRepeat = TRUE;
}
else
{
bTIfRepeat = FALSE;
}
}
/*字符串头部是否存在空格*/
if (str[0] == 32)
{
cntOfWord--;
}
/*字符串尾部是否存在空格*/
if (lastBlankSite == length - 1)
{
cntOfWord--;
}
else if (str[lastBlankSite] == 32 && str[lastBlankSite + 1] == 0)
{
cntOfWord--;
}
cntOfWord += 1;
cntOfEnglishWord = cntOfWord;
cout << "cntOfWord:" << cntOfWord << endl;
return;
}