• c# 获取字符串数组中最长的的字符串并输出最长的字符串


    求字符串数组中最大长度的字符串:

    实质就是比较字符串的长度;

    方案一:

     1  class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             string[] array = {"张三","亲,今天购物了么!","明天你喜欢很久的人要结婚了,你怎么办!","老鼠爱上了猫!","明天会下雪吧!"};
     6            string str= GetLength(array);
     7             Console.WriteLine("最长字符串是:{0}",str);
     8             Console.ReadKey();
     9         }
    10         /// <summary>
    11         /// 获取最长字符串
    12         /// </summary>
    13         /// <param name="array"></param>
    14         /// <returns></returns>
    15         private static string GetLength(string[] array)
    16         {
    17            string str =string.Empty;
    18             for (int i = 0; i < array.Length; i++)
    19             {
    20                 if (str.Length<array[i].Length)
    21                 {
    22                     str = array[i];
    23                 }
    24             }
    25             return str;
    26 
    27         }
    28     }
    View Code

     方案二:

    使用冒泡排序的方法:

     1  class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             string[] array = { "张三", "亲,今天购物了么!", "明天你喜欢很久的人要结婚了,你怎么办!", "老鼠爱上了猫!", "明天会下雪吧!" };
     6             string str = GetLength(array);
     7             Console.WriteLine("最长字符串是:{0}", str);
     8             Console.ReadKey();
     9         }
    10         /// <summary>
    11         /// 使用冒泡排序法
    12         /// </summary>
    13         /// <param name="array"></param>
    14         /// <returns></returns>
    15         private static string GetLength(string[] array)
    16         {
    17             for (int i = 0; i < array.Length-1; i++)
    18             {
    19                 for (int j = 0; j < array.Length-1-i; j++)
    20                 {
    21                     string temp = string.Empty;
    22                     if (array[j].Length<array[j+1].Length)
    23                     {
    24                         temp = array[j];
    25                         array[j] = array[j + 1];
    26                         array[j + 1] = temp;
    27                     }
    28                 }
    29 
    30             }
    31             return array[0];
    32 
    33         }
    34     }
    View Code

     其实两种方法很类似,第一种效率相对高,可以使用Stopwatch测试。

  • 相关阅读:
    CSS 中 Position relative 和 absolute区别
    感受到LDT的好处
    Map数据结构
    break和continue
    vue的ref属性
    css小样式
    搭建vue开发环境
    setTimeout和clearTimeout
    垂直居中
    vertical-align 属性
  • 原文地址:https://www.cnblogs.com/zlp520/p/3551984.html
Copyright © 2020-2023  润新知