Home > front end >  Need to display the average letters of each word in a string and display it
Need to display the average letters of each word in a string and display it

Time:04-24

Here is what I have so far, it is set up to display the total number of words, which I need to keep, or modify to keep to allow the average number of letters in each word to be displayed, please assist anyone if you can. thank you so much!:

private void btnCheck_Click(object sender, EvenArgs e)

{
     string words = tbxArgument.Text.Trim();
     MessageBox.Show("Number of Words: "   CountWords(words));
}

private int CountWords(string words)

{
     string[] allWords = words.Split(' ');
     return allWords.Length;
}

CodePudding user response:

Not sure If this is what you are trying to accomplish.

But this will give you the average length of all the words.

double totalCharacters = 0;
double avgCharacters = 0;
string[] words = new string[] {"Word1","Word2","Word3" } ;


foreach (string tmpString in words)
{
    totalCharacters = totalCharacters   tmpString.Length;
}

avgCharacters = totalCharacters/words.Length;

CodePudding user response:

This is a method that only interate over the string, without making splits that require allocate extra memory. Just an optimization, for entertainment:

public static double GetAvgLetters(string text, out int wordsCount)
{
    wordsCount = 0;
        
    if (string.IsNullOrWhiteSpace(text))
    {
        return double.NaN;
    }

    var lettersCount = 0;

    var isLetter = text[0] != ' ';
    var readingLetter = isLetter;
    for (int i = 0; i < text.Length; i  )
    {
        isLetter = text[i] != ' ';

        if (isLetter != readingLetter)
        {
            readingLetter = isLetter;

            if (readingLetter)
            {
                lettersCount  ;
            }
            else
            {
                wordsCount  ;
            }
        }
        else if (isLetter)
        {
            lettersCount  ;
        }
    }

    if (isLetter == readingLetter && isLetter)
    {
        wordsCount  ;
    }

    return lettersCount / (double)wordsCount;
}

I simply iterate checking the changes between blank and not blank (to count words) and, while reading letters, counting letters. At the end, if we are reading letters and last char is a letter, we must add the last word to count.

  • Related