如何计算平均字长

时间:2012-11-21 18:20:05

标签: c#

我试图计算平均字长,但我不断出现错误。

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);`}

1 个答案:

答案 0 :(得分:2)

当您调用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);