在Java中对齐文本 [英] Justify text in Java

查看:288
本文介绍了在Java中对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取一个整数,它将是后续行的长度。 (文本行永远不会超过提供的长度)。

I have to read in an integer which will be the length of the succeeding lines. (The lines of text will never be longer than the length provided).

然后我必须读入每行文本并将空格转换为下划线均匀可能。例如:

I then have to read in each line of text and convert the spaces to an underscore as evenly as possible. For example:

我输入的行长为30.然后一行文字你好这是一个测试字符串。然后将所有空格转换为下划线并填充,以便文本填充给定的行长度,如下所示: Hello__this__is__a_test_string 。如您所见,原始文本的长度为27个字符,因此要将其填充为30个字符,我必须在原始文本中添加3个额外的空格,然后将这些空格转换为下划线字符。

I would enter the line length of 30. Then a line of text Hello this is a test string. Then all of the spaces will be converted to underscores and padded out so that the text fills the given line length like so: Hello__this__is__a_test_string. As you can see, the original text had a length of 27 characters, so to pad it out to 30 characters I had to add 3 extra spaces to the original text and then convert those spaces to the underscore character.

请您告诉我可以解决这个问题的方法吗?

Please can you advise a way that I can go about this?

推荐答案

我做什么将句子分成单词。然后计算出需要添加多少空格。然后迭代单词并为每个单词添加一个空格,直到用完要添加的空格。如果你有足够的空格,你需要在单词中添加多个单词(比如你有5个单词,但需要添加13个空格),只需将剩余的空格数除以单词数,然后将该数加到每个单词中。先说话。然后你可以取余数并迭代添加空格的单词,直到你完成为止。另外,请确保只向句子中的最后一个单词添加空格。

What I do is split the sentence in to words. Then figure out how many spaces need to be added. Then iterate over the words and add a space to each one until you run out of spaces to add. If you have enough spaces where you need to add more than one to the words (like you have 5 words, but need to add 13 spaces), simply divide the number of spaces left by the number of words, and add that number to each word first. Then you can take the remainder and iterate across the words adding a space until you're done. Also make sure that you only add spaces to all but the last word in the sentence.

这篇关于在Java中对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆