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

本文关键字:单词 索引 句子 使用 | 更新日期: 2023-09-27 18:03:33

如果有多个字符串具有相同的长度(max),我如何找到所有的索引。我现在得到的是第一个索引。有更好的方法吗?

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

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

这是我尝试的解决方案:

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

我将使用LINQ,因为它是c#的方式。

这里有一个小提琴: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);