gpt4 book ai didi

c# - 按字母顺序排列字符串

转载 作者:太空狗 更新时间:2023-10-30 00:47:49 25 4
gpt4 key购买 nike

我正在使用 C# 读取一个 .txt 文件,这个文件有一个单词列表,我需要按字母顺序对列表进行排序

static void Main(string[] args)
{
StreamReader objReader = new StreamReader(
@"C:\Users\thoma\Documents\Visual Studio 2019\Backup Files\data.txt");

string orden = "";
ArrayList arrText = new ArrayList();

while (orden != null)
{
orden = objReader.ReadLine();
if (orden != null) arrText.Add(orden);
}
objReader.Close();

foreach (string sOutput in arrText)
Console.WriteLine(sOutput);

Console.WriteLine("Order alphabetically descendant press 'a': ");
Console.WriteLine("Ordener ascending alphabetical press 'b': ");

orden = Console.ReadLine();

switch (orden)
{
case "a":
string ordenado = new String(orden.OrderBy(x => x).ToArray());
Console.WriteLine(ordenado);
break;
case "b":
Console.WriteLine("");
break;
}

Console.ReadLine();
}

这是我目前拥有的代码。 .txt 文件显示它没有问题,但是当输入 while 语句并按选项时,它不会返回任何内容。

在arrText中存储了.txt文件的单词,这些单词是:'in' 'while' 'are'。

我需要在 while 语句中按下 'a' 键时,按字母顺序显示单词列表:'are' 'in' 'while'。

最佳答案

我会提供一个更好的分离和缩短的版本:

    var choices = new Dictionary<ConsoleKey, bool?>()
{
{ ConsoleKey.D1, true },
{ ConsoleKey.D2, false }
};

var ascending = (bool?)null;
while (ascending == null)
{
Console.WriteLine("Please choose between ascending and descending order.");
Console.WriteLine("Press 1 for ascending");
Console.WriteLine("Press 2 for descending");
var choice = Console.ReadKey(true);
ascending = choices.ContainsKey(choice.Key) ? choices[choice.Key] : null;
}

var lines = File.ReadAllLines("c:/data.txt");
lines = ascending.Value
? lines.OrderBy(x => x).ToArray()
: lines.OrderByDescending(x => x).ToArray();

foreach (var line in lines)
{
Console.WriteLine(line);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);

甚至这样:

    var choices = new Dictionary<ConsoleKey, Func<string[], string[]>>()
{
{ ConsoleKey.D1, xs => xs.OrderBy(x => x).ToArray() },
{ ConsoleKey.D2, xs => xs.OrderByDescending(x => x).ToArray() }
};

var ascending = (Func<string[], string[]>)null;
while (ascending == null)
{
Console.WriteLine("Please choose between ascending and descending order.");
Console.WriteLine("Press 1 for ascending");
Console.WriteLine("Press 2 for descending");
var choice = Console.ReadKey(true);
ascending = choices.ContainsKey(choice.Key) ? choices[choice.Key] : null;
}

var lines = ascending(File.ReadAllLines("c:/data.txt"));

foreach (var line in lines)
{
Console.WriteLine(line);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);

关于c# - 按字母顺序排列字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54917247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com