C# 如何计算平均字长

C# 如何计算平均字长,c#,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 mySce

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

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

调用可枚举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);

您看到的错误是什么?'char'不包含'length'的定义,并且找不到接受'char'类型的第一个参数的扩展方法'length'