find the kth longest word in a string in csharp

To find the kth longest word in a string, you can follow these steps:

  1. Split the string into an array of words using the Split method.
  2. Sort the array in descending order by word length using LINQ's OrderByDescending method.
  3. Retrieve the kth element of the sorted array.

Here's the code snippet that implements the above algorithm:

main.cs
public static string KthLongestWord(string input, int k)
{
    string[] words = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    string word = words.OrderByDescending(w => w.Length).Skip(k - 1).FirstOrDefault();
    return word;
}
258 chars
7 lines

In the above code, the Split method splits the input string into an array of words using a space character as a separator. The OrderByDescending method sorts the resulting array in descending order by word length. The Skip method skips the first k-1 elements of the sorted array, and the FirstOrDefault method returns the kth element or null if the array contains less than k elements.

You can then call the above method with the input string and the desired value of k:

main.cs
string input = "The quick brown fox jumps over the lazy dog";
int k = 2;

string result = KthLongestWord(input, k);
Console.WriteLine(result); // Output: "quick"
162 chars
6 lines

gistlibby LogSnag