I didn't know that it's called 'Justify alignment'. I decided to implement with C#. Process is simple. Get text and line width, split text into words, make them group of words for each line, print line after padding it with seperator so that start and end of a line will be characters as possible as it can.
namespace Justify
{
class Program
{
<summary>
</summary>
<param name="text"></param>
<param name="lineWidth"></param>
<returns></returns>
static List<string> Justify(string text, int lineWidth)
{
var output = new List<string>();
List<List<string>> wordLists = getWords(text, lineWidth);
foreach (var list in wordLists)
{
output.Add(padding(list, lineWidth));
}
return output;
}
static private List<List<string>> getWords(string text, int lineWidth)
{
var output = new List<List<string>>();
string[] words = text.Split(new char[] { ' ' });
int length = 0;
var wordList = new List<string>();
for (int i = 0; i < words.Length; ++i)
{
if (length == 0 && words[i].Length >= lineWidth)
{
wordList.Add(words[i].Substring(0, lineWidth));
if (words[i].Length > lineWidth)
{
words[i] = words[i].Substring(lineWidth, words[i].Length - lineWidth);
i--;
}
output.Add(wordList);
wordList = new List<string>();
}
else if (length + 1 + words[i].Length > lineWidth)
{
output.Add(wordList);
wordList = new List<string>();
length = 0;
i--;
}
else
{
wordList.Add(words[i]);
length += words[i].Length + 1;
}
}
return output;
}
static private string padding(List<string> wordList, int lineWidth)
{
if (wordList.Count == 0)
return string.Empty;
int i = 0;
int length = 0;
foreach (var word in wordList)
{
length += word.Length;
}
while (length < lineWidth)
{
if (i == 0 || i != wordList.Count - 1)
{
wordList[i] = wordList[i] + " ";
length++;
}
i = (i + 1) % wordList.Count;
}
return string.Join<string>("", wordList);
}
static void Main(string[] args)
{
string text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
var output = Justify(text, 30);
foreach (var line in output)
Console.WriteLine(line);
}
}
}
Then the output is,
Lorem ipsum dolor sit amet,
consectetur adipisicing elit,
sed do eiusmod tempor
incididunt ut labore et
dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud
exercitation ullamco laboris
nisi ut aliquip ex ea commodo
consequat. Duis aute irure
dolor in reprehenderit in
voluptate velit esse cillum
dolore eu fugiat nulla
pariatur. Excepteur sint
occaecat cupidatat non
proident, sunt in culpa qui
officia deserunt mollit anim
No comments:
Post a Comment