使用C#的句子中最长单词的索引

时间:2016-08-23 16:08:54

标签: c# string

如果有多个字符串具有相同的长度(最大值),我如何找出所有索引。我目前正在获得第一个索引。有更好的方法吗?

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); 
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这是我的解决方案:

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;
    }
}

然后你可以这样称呼它:

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

这是另一种可能的扩展方法,用于直接查找最长字符串的索引:

    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 so far we ignore it
        }

        return indices;
    }

答案 1 :(得分:1)

我会玩LINQ,因为它是C#-ish方式。

这是一个小提琴:https://dotnetfiddle.net/NEFkqb

List<string> words = new List<string>{"aaaa","bb","cccc"};
List<int> lengths = words.Select(word => word.Length).ToList();
int max = lengths.Max();
List<int> maxes = new List<int>();
for(int i = 0; i < lengths.Count; i++)
  if(lengths[i] == max)
    maxes.Add(i);