C# finding the shortest and longest word in a array

19.8k views Asked by At

I am trying to find the shortest and longest string value based on length and im getting stuck. As of now the script exits after the writeline. I think the code needs some help, I dont think a for loop can work on its own. Any assistance would be appreciated.

        for (int i = 5; i <0; i++)
        {
            string[] word = new string[5];
           Console.WriteLine("Type in a word");
            word[i] = Console.ReadLine();

             int length = word[i].Length;
             int min = word[0].Length;
             int max = word[0].Length;
             string maxx;
             string minn;


              if (length > max)
                 {
                   maxx = word[i];
                   Console.Write("Shortest");
                  }
             if (length < min) 
              {
                 minn = word[i];
                Console.Write("Longest");
              }



         }
        Console.ReadKey(true);
    }
9

There are 9 answers

4
PengWu On BEST ANSWER
string[] word = new string[5];
for (int i = 0; i <= word.Length; i++)
{

    Console.WriteLine("Type in a word");
    word[i] = Console.ReadLine();
}
int min = word[0].Length;
int max = word[0].Length;
string maxx = word[0];
string minn = word[0];
for (int i = 1; i <= word.Length; i++)
{
    int length = word[i].Length;
    if (length > max)
    {
        maxx = word[i];
        max = length;
    }
    if (length < min)
    {
        minn = word[i];
        min = length;
        Console.Write("Longest");
    }
}
Console.Write("Shortest:" + maxx);
Console.Write("Longest" + minn);
Console.ReadKey(true);
0
Arsen On

Your for loop condition is always false. i starts at 5 and you are checking for it to be less than 0... This is always false so the loop never starts.

And if that is just a typo, you are also putting the input into names[i] instead of word[i], and names[i] is never used again...

1
DavidN On

Here's a generic extension method you can use (efficiency O(n)):

public static class Extensions{
    // assumes that supply a Func<T, int> that will return an int to compare by
    public static Tuple<T, T> MaxMin<T>(this IEnumerable<T> sequence, Func<T, int> propertyAccessor){
        int min = int.MaxValue;
        int max = int.MinValue;

        T maxItem = default(T);
        T minItem = default(T);

        foreach (var i in sequence)
        {
            var propertyValue = propertyAccessor(i);
            if (propertyValue > max){
                max = propertyValue;
                maxItem = i;
            }

            if (propertyValue < min){
                min = propertyValue;
                minItem = i;
            }                       
        }

        return Tuple.Create(maxItem, minItem);
}

// max will be stored in first, min in second
var maxMin = word.MaxMin(s => s.Length);
2
Keith Nicholas On

Linq is the way to go here to make your life a lot easier...

var sorted=word.OrderBy(n => n.Length);
var shortest = sorted.FirstOrDefault();
var longest = sorted.LastOrDefault();
0
Bart Calixto On
string[] words = new string[5];
    foreach (string word in words) {

        Console.WriteLine("Type in a word");

        word = Console.ReadLine();

        var ordered = words.Where(w=>!String.IsNullOrEmpty(w)).OrderBy(w=>w.length)

        if (ordered.First() == word) 
            Console.Write("Shortest");
        if (ordered.Last() == word)
            Console.Write("Longest");

        // First time will display both "Shortest" and "Longest" since it's the only word.
        // You may adjust code depending on what do you want to do in case of words of same length.
        Console.ReadKey(true);
    }
}
0
OnoSendai On

As @DStanley and @RenniePet pointed out, your original code doesn't exactly do what you're trying to accomplish. I do believe you wanted to cycle through the member of your string array and fill them with console inputs. A working code would look like this:

    string[] word = new string[5];

        for (int i = 0; i < word.Length; i++)
        {
            Console.Write("Input text: ");
            word[i] = Console.ReadLine();
        }

        List<string> _sortedWords = word.ToList<string>();
        _sortedWords.Sort((x, y) => x.Length.CompareTo(y.Length));

        Console.WriteLine("Smaller: " + _sortedWords[0]);
        Console.WriteLine("Larget: " + _sortedWords[_sortedWords.Count-1]);

        Console.ReadLine();
3
AB Vyas On

try this

    static void Main(string[] args)
    {
        string[] array1 = { "Cats and ratsasdfasdf", "just rats and the just catest", "rats" };
        var shortString = array1[0];
        var longString = array1[0];

        /*Code for Find Shortest and longest string in Array*/
        foreach (var t in array1)
        {
            if (shortString.Length > t.Length)
                shortString = t;
            if (longString.Length < t.Length)
                longString = t;
        }
        Console.WriteLine("shortest string is:" + shortString);
        Console.WriteLine("Longest string is:" + longString);
        Console.Read();
    }
0
terborac On

If you use LINQ, using Max/Min method is a better way than sorting.

var longest = word.Max(s=>s.Length);
var shortest = word.Min(s=>s.Length);
0
Philippe Canavarro On

The Linq OrderBy solution is quite good but will not give you all results in the possibility there is more than 1 string with the max/min lengths.

The solution below will get the biggest string length and return a new array with all the matches, just in case you have more than 1 with the same Max or Min lengths.

Max Length

// Getting the max length strings from the array
int max = word.Max(s =>  s.Length);

// Selecting the values where the length is equal to the max value above
string[] arrayMaxLength = word.Where(s => s.Length == max).ToArray();

Min Length

// Getting the min length strings from the array
int min = word.Min(s => s.Length);

// Selecting the values where the length is equal to the min value above
string[] arrayMinLength = word.Where(s => s.Length == min).ToArray();