Share via


How to Display Longest Word in a File

Question

Saturday, May 19, 2018 10:10 AM

I am doing an exercise, or trying, that asks to display the longest word in a text file.  I am able to determine the number of words in a file.  How do I display the longest word?  Thank You!

using System;
using System.Collections.Generic;
using System.IO;


namespace StringBuilderPractice
{
    class Program
    {
        static void Main(string[] args)
        {

            var path = @"C:\Users\USER\Desktop\BPI Payment Conf 52618.txt";
            var allChars = File.ReadAllText(path);
            var words = new List<string>(allChars.Split(' '));
            Console.WriteLine(words.Count);
            Console.ReadKey();
        }
    }
}

 

All replies (2)

Saturday, May 19, 2018 10:47 AM âś…Answered

You can do like this

1.Initialize longestIndex=1, longestWord = words[0]

Here, longestIndex will be used for storing Position of Longest Word while longestWord actually holds the longest string in the list.

2. Now iterate through loop from word[0] to word[word.Count-1], Compare each item if that item length>longestWord.Length then adjust longestIndex & longestWord.

Like this

        static void Main(string[] args)
        {
            var path = @"C:\Users\USER\Desktop\BPI Payment Conf 52618.txt";
            var allChars = File.ReadAllText(path);
            var words = new List<string>(allChars.Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries));
            Console.WriteLine(words.Count);
            if (words.Count > 0)
            {
                int longestIndex = 1;
                string longestWord = words[0];
                for (int i = 0; i < words.Count; i++)
                {
                    string item = words[i];
                    if (item.Length > longestWord.Length)
                    {
                        longestWord = item;
                        longestIndex = i + 1;
                    }
                }
                Console.WriteLine("Longest Word: {0}\nFound at Position {1}", longestWord, longestIndex);
            }
            Console.ReadKey();
        }

Saturday, May 19, 2018 11:04 AM

I fumbled with that until my mind was no longer able to iterate thoughts :)

Thanks!