C# finding the shortest and longest word in a array

后端 未结 8 1245
小蘑菇
小蘑菇 2021-01-15 04:32

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 h

相关标签:
8条回答
  • 2021-01-15 05:12
    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 讨论(0)
  • 2021-01-15 05:17

    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 讨论(0)
提交回复
热议问题