Text justification

I am looking for a function or C # routine that will center the alignment of text.

For example, if I have a sentence, I noticed that when the sentence is justified by the edges of the screen, these spaces are placed in a line. The inserted spaces begin in the center and, if necessary, move away from both sides as necessary.

Is there a C # function with which I can pass my string, for example, 50 characters, and get a beautiful 56 char string?

Thanks in advance,

Rob

+3
source share
2 answers

. , Linq. , . . "" .

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static String Justify(String s, Int32 count)
    {
        if (count <= 0)
            return s;

        Int32 middle = s.Length / 2;
        IDictionary<Int32, Int32> spaceOffsetsToParts = new Dictionary<Int32, Int32>();
        String[] parts = s.Split(' ');
        for (Int32 partIndex = 0, offset = 0; partIndex < parts.Length; partIndex++)
        {
            spaceOffsetsToParts.Add(offset, partIndex);
            offset += parts[partIndex].Length + 1; // +1 to count space that was removed by Split
        }
        foreach (var pair in spaceOffsetsToParts.OrderBy(entry => Math.Abs(middle - entry.Key)))
        {
            count--;
            if (count < 0)
                break;
            parts[pair.Value] += ' ';
        }
        return String.Join(" ", parts);
    }
    static void Main(String[] args) {
        String s = "skvb sdkvkd s  kc wdkck sdkd sdkje sksdjs skd";
        String j = Justify(s, 5);
        Console.WriteLine("Initial: " + s);
        Console.WriteLine("Result:  " + j);
        Console.ReadKey();
    }
}
+2

, # .net, - ( - , ).

:

Until the required number of characters is reached:
     Extend the shortest sequence of spaces by one
     (choose one randomly if there is more than one such sequence).

, , ( ). , , , .

+1

Source: https://habr.com/ru/post/1725251/


All Articles