【发布时间】:2018-11-27 20:46:08
【问题描述】:
我不知道怎么称呼它,但是有这种排序的算法吗?从输入到输出。
输入:
Article evident arrived express highest men
did boy. Mistress sensible entirely am so.
Quick can manor smart money hopes worth too.
Comfort produce husband boy her had hearing.
Law others theirs passed but wishes. You day
real less till dear read. Considered use dispatched
输出:
Article evident arrived express highest men
did boy. Mistress sensible entirely am so.
Quick can manor smart money hopes worth too.
Comfort produce husband boy her had hearing.
Law others theirs passed but wishes. You day
real less till dear read. Considered use dispatched
这就是我写的所有内容,老实说,我认为这是我技能的顶峰......如果有人可以链接一个与我的问题有些相关的教程,我将不胜感激。
int highestnr = 0;
string[] lines = File.ReadAllLines(Text, Encoding.GetEncoding(1257));
for (int i = 0; i < lines.Length; i++)
{
string[] parts = lines[i].Split(seperators, StringSplitOptions.RemoveEmptyEntries);
for (int k = 0; k < parts.Length; k++)
{
if (parts[k].Length > highestnr)
{
highestnr = parts[k].Length;
}
}
}
using (var write = File.CreateText(Results))
{
foreach(var something in lines)
{
string[] parts = something.Split(seperators, StringSplitOptions.RemoveEmptyEntries);
StringBuilder NewLine = new StringBuilder();
for (int i = 0; i < parts.Length; i++)
{
NewLine.Append(' ', highestnr);
NewLine.Append(parts[i]);
}
write.WriteLine(NewLine);
}
}
我知道代码只根据最高字数给出空格,而不是按列分隔,这超出了我的范围......
【问题讨论】:
-
@Hogan 我花了 3 条语句,其中一条是 3 行,因为我将 LINQ 方法调用放在单独的行上。考虑两个参数
Select和GroupBy的用处。 -
不使用 LINQ,我的一般做法是将
String.Split您的源代码 (List<string>) 转换为单词 (List<string[]>) 并存储在变量中。然后找到一行中的最大单词,并找到每个单词位置的最大长度单词(从0到max)。现在您只需再次处理单词列表,使用PadRight将每行中的每个单词重新格式化为您为该位置找到的最大长度,然后String.Join将单词重新转换为句子。 -
@NetMage -- 有道理。 linq 中的 3 行代码很多,因为大多数事情都可以在一行中完成。
-
查看您的示例代码,将
highestnr更改为最大parts.Length上的数组(仅选择1000 之类的数字会很糟糕,但OTOH 动态增长List是有点棘手),然后在找到每个位置的最大值时按k索引highestnr。然后在输出时用i索引highestnr,并交换parts[i]的输出和空格(或使用String.PadRight)。 -
对不起,我试图弄清楚你对我的意义,但我不知道。我试图将highestnr解析为一个数组,但当时我不能将它声明为0,然后它就不允许我比较并找到最高的数字。