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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM