簡體   English   中英

如何計算平均字長

[英]How to calculate average word length

我試圖計算平均字長,但我不斷出現錯誤。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace textAnalyser
{
public class Analyser
{
public static void Main()
{
// Values
string myScen;
string newScen = "";
int numbChar = 0;
string userInput;
int countedWords = 0;

//User decsion on how to data is inputted
Console.WriteLine("Enter k for keyboard and r for read from file");
userInput = Convert.ToString(Console.ReadLine());

//If statement, User input is excecuted

if (userInput == "k")
{
// User enters their statment
Console.WriteLine("Enter your statment");
myScen = Convert.ToString(Console.ReadLine());

// Does the scentence end with a full stop?

if (myScen.EndsWith("."))
Console.WriteLine("\n\tScentence Ended Correctly");

else
Console.WriteLine("Invalid Scentence");

計算單詞中的字符數

// Calculate number of characters
foreach (char c in myScen)
{
numbChar++;
if (c == ' ')
continue;

newScen += c;
}
Console.WriteLine("\n\tThere are {0} characters. \n\n\n", numbChar);

// Calculates number of words
countedWords = myScen.Split(' ').Length;
Console.WriteLine("\n\tTherer are {0} words. \n\n\n", countedWords);

這是我試圖計算平均字長//計算平均字長的地方

double averageLength = myScen.Average(w => w.Length);
Console.WriteLine("The average word length is {0} characters.", averageLength);`}

當您調用Enumerable LINQ方法(如.Average()或.Where())時,它們會對集合中的各個元素進行操作。 字符串是一個字符集合,因此myScen.Average()語句循環遍歷字符串的每個字符,而不是每個單詞。 字符都是長度為1,因此它們沒有長度屬性。

為了能夠訪問單個單詞,您必須在myScen上調用.Split(''),它為您提供字符串的集合(特定的數組)。 由於這些字符串具有長度,您可以對它們進行平均並使用最終結果。

var countedWords= myScen.Split(' ').Average(n=>n.Length);
Console.WriteLine("\n\tTherer are {0} words. \n\n\n", countedWords);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM