Closed. This question needs details or clarity。它当前不接受答案。












想改善这个问题吗?添加详细信息并通过editing this post阐明问题。

6年前关闭。



Improve this question





如何在不切断单词的情况下自动将行分成多行?每行的长度约为4个字?我有很多句子,所以我不能使用\n

例如:

If I were you I would go to the cinema with her


变成:

If I were you
I would go to
the cinema with her


希望很快能对您有所帮助。谢谢!

最佳答案

我可以想象,尽管您不确定我是否正在考虑所有可能的情况,但还是根据您的意见,提出了一种方法,可以在想当然而又不直接依赖“ \ n “ 将会...

    String s = "If I were you I would go to the cinema with her";
    String[] strings = s.split(" ");
    for(int i = 0; i < strings.length; ++i) {
        if(i % 4 == 0) {
            System.out.println();
        }
        System.out.print(strings[i] + " ");
    }


或者,您可能会考虑使用类似这样的方法,它可以处理文本字段的最大宽度,而不是一定数量的单词,因为某些单词可能很长,并导致您要避免的情况...

    int MAX = 20;
    int length = 0;
    String s = "If I were you I would go to the cinema with her.";
    String[] strings = s.split(" ");
    for(int i = 0; i < strings.length; ++i) {
        if((length + strings[i].length()) > MAX ) {
            System.out.println();
            length = 0;
        }
        System.out.print(strings[i] + " ");
        length += strings[i].length() + 1;
    }


编辑:
我照你的要求做了。这就是我从MAX选项中得到的...

If I were you I
would go to the
cinema with her and
abc xyz


这就是我经常得到的...

If I were you
I would go to
the cinema with her
and abc xyz


不知道那里发生了什么,但是我会说我对答案很感兴趣。您已经标记了Android,并且我和我俩都知道System.out.println()在那种环境下是禁忌,至少如果您希望看到任何结果的话。对于那个很抱歉。

07-26 09:36
查看更多