gpt4 book ai didi

java - 断线 - Android

转载 作者:行者123 更新时间:2023-12-01 13:49:59 25 4
gpt4 key购买 nike

如何在不截断单词的情况下自动将一行分成多行?每行的长度大约是 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() 在该环境中是禁忌,至少如果您希望看到任何结果的话。对此感到抱歉。

关于java - 断线 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com