2012-11-21 73 views
0

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

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

你看到的错误是什么? – Beska

+0

'char'不包含'length'的定义,并且没有可以找到'char'类型的第一个参数的扩展方法长度<是否缺少using指令或程序集引用:> – user1832076

回答

2

当你调用诸如.Average()或.Where()之类的可枚举LINQ方法,它们对集合中的各个元素进行操作。一个字符串是一个字符集合,所以你的myScen.Average()语句循环遍历字符串的每个字符,而不是每个字。字符都是长度为1的字符,所以它们没有长度属性。

为了访问单个单词,您必须在myScen上调用.Split(''),这会为您提供一个字符串的集合(一个特定的数组)。由于这些字符串具有长度,因此您可以对它们进行平均并使用最终结果。

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