【问题标题】:Find the shortest string in an array of string在字符串数组中找到最短的字符串
【发布时间】:2017-06-23 09:54:36
【问题描述】:

我需要提供一种解决方案来找到字符串数组中最短的字符串。我在想应该比较每个字符串的长度才能返回。

这就是我被困的地方

static void Main(string[] args)
{
    //find the shortest string in an array of string
    string[] names = new string[3]{
        "Tom", "and", "jerry"
    };

    foreach(string name in names){
        Console.Write(name + ", ");
    }

    Console.ReadKey();
}

谁能帮我比较一下并解释一下

【问题讨论】:

  • everyone...是的,这正是您在这里获得帮助的方式...
  • 由于“Tom”和“and”的长度相同,您期望在您的示例中得到什么结果?
  • 您会将哪个分类为最短的字符串,“Tom”或“and”?你试过什么?

标签: c# arrays .net string


【解决方案1】:

这将找到第一个最短的字符串而不对集合进行排序:

int minLength = names.Min(y=>y.Length); // this gets you the shortest length of all elements in names
string shortest = names.FirstOrDefault(x=>x.Length == minLength);

说明:它将检查长度等于整个集合中最小长度的元素。

编辑:

谁能帮我比较一下并解释一下

要比较字符串的长度,请使用Length 属性和== 运算符。当然,您也可以像 ChoockY 那样在循环中执行此操作。

【讨论】:

    【解决方案2】:

    使用LINQ:

    var shortestString = names.OrderBy(c => c.Length).FirstOrDefault();
    

    【讨论】:

    • 排序比简单的线性搜索要慢。
    • @adjan 这不是某人投反对票的好理由。 Downvotes 是针对非常糟糕的尝试或不正确的答案!
    • 就我个人而言,我并没有贬低你,因为你的回答在技术上符合 OP 的要求。但正如已经指出的那样,在这种情况下,排序是浪费时间。我当然不会推荐它,尤其是对新手。投反对票是完全合理的。
    【解决方案3】:

    你可以用 linq 做到这一点,

    var shortestName = names.OrderBy(name => name.Length).FirstOrDefault();
    

    string shortestName = names.Aggregate((a1, a2) => a1.Length <a2.Length ? a1 : a2);
    

    【讨论】:

    • 如果nameslist 中没有条目,这将以异常结束。我会改用FirstOrDefault
    【解决方案4】:

    正如其他人所说,您可以使用 LINQ。这是完成这项工作的最简单方法,但我认为,你应该学习一些算法。在数组中求最小值/最大值属于编程基础。

    您可以在这里阅读: http://www.stoimen.com/blog/2012/05/21/computer-algorithms-minimum-and-maximum/

    纯c#实现如下:

    string[] names = new string[3]{
         "Tom", "and", "jerry"
    };
    
    string minValue = names[0];
    foreach (string name in names)
    {
         if (name.Length < minValue.Length)
         {
              minValue = name;
         }
    }
    
    Console.WriteLine(minValue);
    

    【讨论】:

    • 同意。另外,我可能会补充一点,在这种情况下,排序是一种无用的浪费时间。
    • 谢谢你,它成功了,我被困在寻找最大/最小部分但你救了我,感谢大家的帮助。
    【解决方案5】:

    您可以为此使用MaxBy。请不要为了找到最大值而对整个序列进行排序。这是非常浪费的,故意浪费是会扼杀软件性能的毒瘤。

    【讨论】:

    • 也许 MinBy 会更好?
    • @MartinMulder 你说得对,谢谢。我倾向于在必要时只使用 MaxBy 和翻转符号,但你是对的。
    【解决方案6】:

    没有人在 O(N) 时间内以单行方式提供答案。更好的解决方案是使用 .Aggregate:

    var shortest = names.Aggregate((s, best) => s.Length < best.Length ? s : best)
    

    【讨论】:

    【解决方案7】:

    也许你可以这样做:

    string[] names = new string[3]{
     "Tom", "and", "jerry"
    };
    var query = from n in names select n.Length;
    Console.WriteLine("Shortest name: " + names[Array.IndexOf(query.ToArray(), query.ToArray().Min())]);
    

    我希望这对某人有用

    【讨论】:

      【解决方案8】:

      编写自己的 Linq,如下所示:

      public static T1 Min<T1, T2>(this IEnumerable<T1> source, Func<T1, T2> selector) where T2 : IComparable<T2> {
          if (source == null) {
              throw new ArgumentNullException(nameof(source));
          }
      
          if (selector == null) {
              throw new ArgumentNullException(nameof(selector));
          }
      
          bool firstIteration = true;
      
          T2 minimum = default;
          T1 value = default;
      
          foreach (T1 v in source) {
              T2 current = selector.Invoke(v);
      
              if (current == null) {
                  throw new NullReferenceException();
              }
      
              if (firstIteration || current.CompareTo(minimum) < 0) {
                  minimum = current;
                  value = v;
                  firstIteration = false;
              }
          }
      
          return value;
      }
      

      这些变量名不好。由你来改进它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多