C#使所有行的长度相同,从文本文件中添加空格

时间:2018-11-26 15:14:48

标签: c# line

我有文本文件,所以看起来像这样。

Some old wounds never truly heal, and bleed again at the slightest word.
Fear cuts deeper than swords.
Winter is coming.
If I look back I am lost.
Nothing burns like the cold.

我需要使这些行的长度与最长的那一行相同

static void Reading(string fd, out int nr)
{
    string[] lines = File.ReadAllLines(fd, Encoding.GetEncoding(1257));
    int length = 0;
    nr = 0;
    int nreil = 0;
    foreach (string line in lines)
    {
        if (line.Length > length)
        {
            length = line.Length;
            nr = nreil;
        }
        nreil++;
    }
}

编辑:只需在句子之间用单词之间的空格填充

1 个答案:

答案 0 :(得分:3)

编辑:由于OP指定了他们想要单词之间的间距,因此我删除了行尾填充示例,仅保留了对齐代码。

string[] lines = File.ReadAllLines(fd, Encoding.GetEncoding(1257));
int maxLength = lines.Max(l => l.Length);
lines = lines.Select(l => l.Justify(maxLength)).ToArray();

public static string Justify(this string input, int length)
{
    string[] words = input.Split(' ');
    if (words.Length == 1)
    {
        return input.PadRight(length);
    }
    string output = string.Join(" ", words);
    while (output.Length < length)
    {
        for (int w = 0; w < words.Length - 1; w++)
        {
            words[w] += " ";
            output = string.Join(" ", words);
            if (output.Length == length)
            {
                break;
            }
        }
    }
    return output;
}