【c++】计算句子中单词的平均长度

Description

编程输入一行文本,计算这行文本的单词平均长度。假设每个单词用至少一个空格或者标点(英文逗号、句号)隔开。使用C++ string类型。

Input

输入一行文本,不包含数字

Output

输出平均单词长度

Sample Input

hello, how are you

Sample Output

3.5

 

解题思路:

第一步计算出句子中所有字母的个数letterNum,第二步计算出句子中单词的个数wordNum(关键),第三步求出单词平均长度:letter / wordNum。

 

#include <iostream>
#include <string>

using namespace std;

bool isSeparator(char ch);  //判断一个字符是不是分隔符(空格、逗号,句号)
int cntChar(string str);    //计算句子中字母数的函数
int cntWord(string sentence);   //计算句子中单词个数的函数

int main()
{
    string sentence;
    getline(cin, sentence);
    int letterNum = cntChar(sentence);
    int wordNum = cntWord(sentence);
    cout << letterNum*1.0 / wordNum;
    return 0;
}

int cntWord(string sentence)
{
    int wordNum = 0;
    int len = sentence.length();
    int i = 0;
    while (true)
    {
        //如果是分隔符,就跳过
        if (isSeparator(sentence[i]))
        {
            while (i <= len-1 && isSeparator(sentence[i]))
                i++;
        }
        //如果不是分隔符,就说明遇到单词,wordNum++,然后逐步跳过该单词
        else if (!isSeparator(sentence[i]))
        {
            wordNum++;
            while (i <= len-1 && !isSeparator(sentence[i]))
                i++;
        }
        if (i > len-1)
            break;
    }
    return wordNum;
}

bool isSeparator(char ch)
{
    if (ch == ' ' || ch == ',' || ch == '.')
        return true;
    return false;
}

int cntChar(string str)
{
    int len = str.length();
    int cnt = 0;
    for (int i = 0; i < len; i++)
    {
        if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
            cnt++;
    }
    return cnt;
}

 

 

原文地址:https://www.cnblogs.com/huwt/p/10632084.html