Search code examples
c#arraysstringline

Getting multiple strings of the same lenght from array


i need to take the longest line, or multiple if there is, out of string array of lines and write it out in console together with its posision in the array, i managed to find the longest one but im unable to find multiple strings. Can anyone help? (sorry if this is hard to understand).


Solution

  • One way you could do this is store the longest lines and their indexes in a dictionary. Start with a temporary variable to hold the longest line, and then walk through the array. As we find lines that are equal length, add them to our dictionary. If we find a longer line, set the dictionary to a new one, with just that line added to it, and continue.

    For example:

    public static void PrintLongestLinesAndIndexes(string[] input)
    {
        if (input == null)
        {
            Console.WriteLine("No data");
            return;
        }
    
        var longestLine = string.Empty;
        var longestLines = new Dictionary<int, string>();
    
        for (int i = 0; i < input.Length; i++)
        {
            // If this line is longer, reset our variables
            if (input[i].Length > longestLine.Length)
            {
                longestLine = input[i];
                longestLines = new Dictionary<int, string> {{i, input[i]}};
            }
            // If it's the same length, add it to our dictionary
            else if (input[i].Length == longestLine.Length)
            {
                longestLines.Add(i, input[i]);
            }
        }
    
        foreach (var line in longestLines)
        {
            Console.WriteLine($"'{line.Value}' was found at index: {line.Key}");
        }
    }
    

    Then we can use it like:

    public static void Main(string[] args)
    {
        PrintLongestLinesAndIndexes(new[]
        {
            "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine", "ten"
        });
    
        GetKeyFromUser("\nDone! Press any key to exit...");
    }
    

    Output

    enter image description here


    Another way to do this would be to use Linq to select the items and their indexes, group them by the item's length, then order them by the length and select the first group:

    public static void PrintLongestLinesAndIndexes(string[] input)
    {
        Console.WriteLine(string.Join(Environment.NewLine,
            input.Select((item, index) => new {item, index})
                .GroupBy(i => i.item.Length)
                .OrderByDescending(i => i.Key)
                .First()
                .Select(line => $"'{line.item}' was found at index: {line.index}")));
    }