find the longest word in a string in csharp

Here's the code snippet to find the longest word in a string in C# using loops and functions:

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

int maxLength = 0;
string longestWord = "";
foreach (string word in words)
{
    if (word.Length > maxLength)
    {
        maxLength = word.Length;
        longestWord = word;
    }
}

Console.WriteLine("Longest word is: " + longestWord);
344 chars
16 lines

We first split the sentence into an array of words using the Split() function. Then we initialize variables to store the maximum length and the longest word found so far. We loop through each word in the array and check if its length is greater than the current maximum length. If it is, we update the variables. Finally, we print out the longest word found.

gistlibby LogSnag