Beginner Beginner - 2 months ago 9
C# Question

How to find the largest word from the string using C#?

This is my code for finding the largest word from a given string. I have got the length of all the words in the string now how do I get the largest word to be printed out? I have tried to get all the largest words but am not able to do using this code plz help?

using System;
using System.Linq;
class largest1{
public void largest(){
Console.WriteLine("Enter the String:");

string buffer1 = Console.ReadLine();
string[] buffer = buffer1.Split(' ');
int length;
string largestword = buffer[0];

for(int i = 0; i < buffer.Length; i++){
string temp = buffer[i];
length = temp.Length;

if( largestword.Length < buffer[i].Length ) {
largestword = buffer[i];
}
}

var largestwords = from words in buffer
let x = largestword.Length
where words.Length == x
select words;

Console.Write("Largest words are:");
foreach(string s in largestwords){
Console.Write(s);
}
}

static void Main(){
largest1 obj = new largest1();
obj.largest();
}
}

Answer
//Put this in your class so that it is persisted
string largestword = "";

//Put this right before your for loop
largestword = buffer[0];

//Put this inside your for loop
if( largestword.Length < buffer[i].Length ) {
     largestword = buffer[i];
}

EDITED: Added support for multiple words of the same length

class LargestWordsClass
{
    public LargestWordsClass()
    {
        _LargestWords = new List<String>();
    }

    //This says that the variable can be set from the class but read by anyone
    public int LargestWordSize
    {
        get;
        private set;
    }

    //This lets users get the list without being able to modify it
    private List<String> _LargestWords;
    public String[] LargestWords
    {
        get
        {
            return _LargestWords.ToArray();
        }
    }

    public void FindLargestWord()
    {
        _LargestWords.Clear();

        Console.WriteLine("Enter the String: ");
        String buffer = Console.ReadLine();
        String[] splitBuffer = buffer.Split(' ');

        LargestWordSize = 0;
        for (int i = 0; i < splitBuffer.Length; i++)
        {
            if (LargestWordSize < splitBuffer[i].Length)
            {
                LargestWordSize = splitBuffer[i].Length;
                _LargestWords.Clear();
                _LargestWords.Add(splitBuffer[i]);
            }
            else if (LargestWordSize == splitBuffer[i].Length)
            {
                _LargestWords.Add(splitBuffer[i]);
            }

            Console.WriteLine("The word is " + splitBuffer[i] + " and the length is " + splitBuffer[i].Length.ToString());
        }

        Console.WriteLine("The largest word" + ((_LargestWords.Count > 1) ? "s are" : " is:"));
        for (int i = 0; i < _LargestWords.Count; i++)
        {
            Console.WriteLine(_LargestWords[i]);
        }
    }
}