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.cs250 chars7 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