How to find the longest word in a string with C#

2 Answers

0 votes
using System;
using System.Linq;

class Program
{
    static string LongestWord(string s) {
        var words = s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
        
        return words.OrderByDescending(w => w.Length).First();
    }

    static void Main()
    {
        Console.WriteLine(LongestWord("Could you recommend a good restaurant nearby?"));
    }
}



/*
run:

restaurant

*/

 



answered Mar 2 by avibootz
0 votes
using System;

class Program
{
    static string LongestWord(string s) {
        var words = s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
        string longest = "";

        foreach (var w in words) {
            if (w.Length > longest.Length)
                longest = w;
        }

        return longest;
    }

    static void Main()
    {
        Console.WriteLine(LongestWord("Could you recommend a good restaurant nearby?"));
    }
}



/*
run:

restaurant

*/

 



answered Mar 2 by avibootz
...