c # делает все строки одинаковой длины, добавляя пробелы из текстового файла - PullRequest
0 голосов
/ 26 ноября 2018

У меня есть текстовый файл, поэтому он выглядит следующим образом.

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

edit: простозаполнение предложений пробелами между словами

1 Ответ

0 голосов
/ 26 ноября 2018

РЕДАКТИРОВАТЬ: Так как 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;
}
...