CodeX CodeX - 3 months ago 17
C# Question

Index of longest word in a sentence using C#

If there are multiple string with same length(max), how do I find out all the indices. I am getting the first index currently. Is there a better way to do this?

using System;
using System.Linq;

namespace Examples
{
class Program
{
static void Main(string[] args)
{
Longestword("Find the largest word with lower index abcdefg ");
Console.ReadKey();
}

private static void Longestword(String sen)
{
String[] sArray = sen.Split(null);
int[] cArr = new int[sArray.Length];

for (int i = 0; i < sArray.Length; i++)
{
int j = sArray[i].Length;
cArr[i] = j;
}
int max = cArr.Max();
int index = cArr.ToList().IndexOf(max);
Console.WriteLine(index);
}
}
}

Answer

Here's my stab at a solution:

public static class LinqExtensions
{
    public static List<int> IndicesOf(this int[] array, int item)
    {
        var indices = new List<int>();

        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] == item)
                indices.Add(i);
        }

        return indices;
    }
}

You can then call it like this:

int[] someArrayFindMax = new[] { 1, 4, 45, 23, 4, 3342, 34, 3342, 4, 3342, 3342 };
int max = someArrayFindMax.Max();
List<int> indices = someArrayFindMax.IndicesOf(max);

Here's another possible extension method for finding the indices of the longest strings directly:

    public static List<int> LongestStringIndices(this string[] strings)
    {
        int longestString = -1;
        var indices = new List<int>();

        for (int i = 0; i < strings.Length; i++)
        {
            if (strings[i].Length > longestString)
            {
                longestString = strings[i].Length;
                // We're no longer interested in the indices of the
                // strings we now know to be shorter
                indices.Clear();
                indices.Add(i);
            }
            else if (strings[i].Length == longestString)
            {
                indices.Add(i);
            }
            // If it's less than the max length we ignore it
        }

        return indices;
    }
Comments