繁体   English   中英

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

[英]c# making all lines same length adding spaces from text file

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

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++;
    }
}

编辑:简单地用单词之间的空格填充句子

编辑:由于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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM