java - 在java中剪切字符串而不破坏单词的中间

标签 java android regex

<分区>

如何截断文本而不在单词中间剪切?

例如,我有字符串:

"A totally fresh and new approach to life itself emerges. Once again, you’re off to a good start, willing to do that little bit extra in your result-oriented frame of mind. It’s not the amount of effort but the results that matter to you. You also gain much in the depth of the romance and emotional bonds in your life. This is a good time for self-improvement programs or philanthropy, alms-giving and charity."

如果我要剪,我想这样剪:

"A totally fresh and new approach to life itself emerges. Once again, you’re off to a good start, willing to do that little bit extra in your result-oriented frame of mind. It’s not the amount of effort but the results that matter to you. You also gain much in the depth of the romance and"

而不是:

"A totally fresh and new approach to life itself emerges. Once again, you’re off to a good start, willing to do that little bit extra in your result-oriented frame of mind. It’s not the amount of effort but the results that matter to you. You also gain much in the depth of the romance and emoti"

最佳答案

在此方法中,传递您的字符串和最后一个索引,直到您想要截断为止。

public String truncate(final String content, final int lastIndex) {
    String result = content.substring(0, lastIndex);
    if (content.charAt(lastIndex) != ' ') {
        result = result.substring(0, result.lastIndexOf(" "));
    }
    return result;
}

关于java - 在java中剪切字符串而不破坏单词的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188522/

相关文章:

java - 将可序列化的自定义对象读取到文件android中

java - 如何编写一个以 fragment 类作为参数的方法,该方法将允许我创建该 fragment 的新实例?

javascript - 如何获取组的值并在 JavaScript 的一行中定义它?

java - 如何在java中使用正则表达式在给定单词之后提取java中的单词

java - ListNode解决方案需要说明

java - 在 Java Future 上使用 isDone 和 Cancel 轮询而不是阻塞 get

android - 无法找到位置应用程序崩溃

android - adb shell su 有效,但 adb root 无效

android - 尝试编译 android 内核代码时出错?

java - 不同 tomcat 日志条目的正则表达式模式