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

时间:2013-06-19 10:07:38

标签: java android regex

如何在一个单词的中间截断一个没有剪切的文本?

例如,我有字符串:

  

“一种全新的生活方式出现了。再一次,   你有一个好的开始,愿意多做一点   以结果为导向的心态。这不是努力的数量而是   结果对你很重要。你也获得了很多深度   你生活中的浪漫和情感纽带。这是个好时机   自我改善计划或慈善事业,施舍和慈善事业。“

如果我剪了它,我想这样切:

  

“一种全新的生活方式出现了。再一次,   你有一个好的开始,愿意多做一点   以结果为导向的心态。这不是努力的数量而是   结果对你很重要。你也获得了很多深度   浪漫和“

而不是:

  

“一种全新的生活方式出现了。再一次,   你有一个好的开始,愿意多做一点   以结果为导向的心态。这不是努力的数量而是   结果对你很重要。你也获得了很多深度   浪漫和情感“

3 个答案:

答案 0 :(得分:9)

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

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;
}

答案 1 :(得分:1)

来自Apache Commons的

WordUtils.wrap(String str, int wrapLength)

答案 2 :(得分:0)

这将在中间(或多或少)剪切字符串。

public static void main(String[] args) {
    String s = "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.";
    int middle = s.length() / 2;
    while(s.charAt(middle) != ' ') {
        middle++;
    }
    String start = s.substring(0, middle);
    String end = s.substring(middle, s.length());
    System.out.println(start);
    System.out.println(end);
}