How to find the second largest word in a string with C#

1 Answer

0 votes
using System;
using System.Linq;

public class Program
{
    public static string FindSecondLargestWordInString(string s) {
        string secondLongest = s.Split(" ")
                .OrderByDescending(x => x.Length)
                .Skip(1)
                .FirstOrDefault();

        return secondLongest;
    }

    public static void Main(string[] args)
    {
        string s = "c cpp cobol c# python java";

        string secondLongest = FindSecondLargestWordInString(s);

        if (secondLongest != null) {
            Console.WriteLine("The second longest word is: " + secondLongest);
        }
        else {
            Console.WriteLine("No second longest word found.");
        }
    }
}


 
/*
run:
   
The second longest word is: cobol
   
*/

 



answered Jun 2, 2024 by avibootz

Related questions

1 answer 119 views
1 answer 95 views
1 answer 90 views
1 answer 95 views
1 answer 102 views
1 answer 92 views
1 answer 117 views
...