find the shortest word in a string in csharp

One way to find the shortest word in a string in C# is to split the string into an array of words, and then use LINQ to find the shortest word. Here's the code:

main.cs
string input = "The quick brown fox jumps over the lazy dog";
string[] words = input.Split(' ');

string shortestWord = words.OrderBy(word => word.Length).First();

Console.WriteLine("Shortest word: " + shortestWord); // Output: "Shortest word: The"
250 chars
7 lines

In this code, the Split method is used to split the input string into an array of words using a space character as the delimiter. Then, the array of words is sorted by the length of each word using the OrderBy method, and the first (i.e. shortest) word is selected using the First method.

Note that this code assumes that the input string contains at least one word. If the input string is empty or contains only whitespace, an empty array of words will be produced, and calling First will throw an exception.

gistlibby LogSnag