java - 断线 - Android

标签 java android string

如何在不截断单词的情况下自动将一行分成多行?每行的长度大约是 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/

相关文章:

java - 将多个流优化为单个循环

java - 使用 Thymeleaf 在 EL 表达式中进行类型转换

java - 使用Java FTDI lib - jd2xx - openport1.3 USB电缆创建OBD2 MUT扫描仪

java - 如何获取通知FCM android中的数据

php - 使用正则表达式删除字符串中不需要的字符

java - 如果使用 Java Smack API 连接中断,如何在使用 nextResult() 时了解或捕获异常?

java - 如何让flatMap在后台线程执行

android - 发送短信android后更新数据库

python - 在 Python 中将撇号保存在 re.sub 中

r - 如何在数据框其他列的一列中搜索字符串