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

查看:43
本文介绍了在 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.然后所有空格将被转换为下划线并填充,以便文本填充给定的行长度,如下所示: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天全站免登陆