簡體   English   中英

如何獲取從最小到最大的字符串長度 C#

[英]How to get length of string from the smallest to the largest C#

底部是 txt 文件中的 readbyline 行,單詞被它們之間的空格分隔( " " )如何排序並返回從最小到最大的長度?

這就是我現在擁有的 - 點擊鏈接:

圖片鏈接

編碼

if (System.IO.File.Exists(textFile))
{
    using (System.IO.StreamReader file = new System.IO.StreamReader(textFile))
    {
        int counter = 0;
        string words; 
        string[] line;

        while ((words = file.ReadLine()) != null)
        {
            line = Regex.Split(words, " ");

            foreach (string line_1 in line)
            {
                Console.WriteLine(line_1 + " " + line_1.Length);
            }

            Console.WriteLine(" ");
            counter++;

            Console.WriteLine("Line[{1}]: {0}\n", words, counter);
        }

        file.Close();
        Console.WriteLine(" ");
        Console.WriteLine("File has [{0}] Lines.", counter);
    }
} 

使用 Linq,您將獲得最小和最大長度,如下所示。

var min = words.Split(' ').Min(s => s.Length);
var max = words.Split(' ').Max(s => s.Length);

如果您需要按排序的所有單詞,請在下面使用。

var sortedList = words.Split(' ').Select(s=>new {Word=s,WordLength=s.Length }).OrderBy(o=>o.WordLength);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM