C# finding the shortest and longest word in a array

后端 未结 8 1259
小蘑菇
小蘑菇 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);
        }
    }
    

提交回复
热议问题