简体   繁体   中英

How to calculate average word length

I have tried to calculate the average word length but I keep getting an error appear.

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");

Calculating the number of characters in a word

// 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);

This is where I have tried to calculate the average word length //Calculate Average word length

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

When you call Enumerable LINQ methods such as .Average() or .Where() they operate on the individual elements within the collection. A string is a collection of characters, so your myScen.Average() statement is looping through each character of the string, not each word. Characters are all of length one, so they have no length property.

In order to get access to individual words, you must call .Split(' ') on myScen which gives you a collection (an array to be specific) of strings. Since these strings have length, you can average them and use your final result.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM