【问题标题】:Getting multiple strings of the same lenght from array [closed]从数组中获取多个相同长度的字符串[关闭]
【发布时间】:2019-12-02 22:32:17
【问题描述】:

我需要从行的字符串数组中取出最长的行或多行,并将其连同它在数组中的位置一起写在控制台中,我设法找到了最长的一行,但我无法找到多行字符串。任何人都可以帮忙吗? (对不起,如果这很难理解)。

【问题讨论】:

  • 您应该显示您用来查找最长行的代码,以便我们可以看到您需要帮助的地方。
  • "(抱歉,如果这很难理解)" -- 是的。我们喜欢代码和示例数据。 minimal reproducible example
  • 而不是写(“对不起,如果这很难理解”)你应该尝试更好地解释你想要归档的内容。

标签: c# arrays string line


【解决方案1】:

您可以这样做的一种方法是将最长的行及其索引存储在字典中。从一个临时变量开始保存最长的行,然后遍历数组。当我们找到长度相等的行时,将它们添加到我们的字典中。如果我们找到更长的行,请将字典设置为新的,仅添加该行,然后继续。

例如:

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

那么我们可以像这样使用它:

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

输出


另一种方法是使用Linq 选择项目及其索引,按项目的长度对它们进行分组,然后按长度对它们进行排序并选择第一组:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多