截断字符串以限制其长度的最佳方法是什么?

时间:2017-03-28 01:47:37

标签: java string

我正在编写一个限制句子长度的函数。说限制是15,句子是" SO是伟大的网站"。我不想在第15个位置完全截断它,否则截断的句子将成为" SO是伟大的网络"。但是,我想要做的是从限制之前的第一个空格截断。它会给我" SO很棒"。

这样做的一种方法是

  

int firstIndexOfSpaceBeforeGIvenIndex = str.lastIndexOf("",15);

     

str = StringUtils.truncate(str,0,firstIndexOfSpaceBeforeGIvenIndex);

字符串可能很长,我必须在数千个字符串上执行此操作。所以表现是我关注的问题。实现这项任务的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

这是一种实用方法,可以满足您的要求并接受@David Wallace和@Ole V.V的评论。也考虑到了:

public static String truncate(String str, int length, String delim) {
    int len = Math.max(0, length);
    if (str.length() <= len) return str;
    else {
        int idx = str.lastIndexOf(delim, len);
        return str.substring(0, idx != -1 ? idx : len);
    }
}
  • 它应该是高效的,因为它首先执行最小扩展操作。
  • 它解决了在第一个delim字符中找不到length的情况。
  • 根据长度分隔符,它非常灵活。

答案 1 :(得分:-1)

用法

select check, sum(case when cnt = 1 then 1 else 0 end) as cnt_1,
       sum(case when cnt >= 2 then 1 else 0 end) as cnt_2plus
from (select check, email, count(*) as cnt
      from t
      group by check, email
     ) ce
group by check;

代码

truncate("SO is great website",15); //"SO is great"
truncate("SO is great website",11); //"SO is great"
truncate("SO is great website",1); //""

测试

private String truncate(String s, int limit) {
    int n = s.length();
    int last = Math.min(n, limit);

    if (last < n) {
        //scroll to start index of the last word
        while (last > 0 && !Character.isWhitespace(s.charAt(last))) last--;
    }

    //strip last whitespaces
    while (last > 0 && Character.isWhitespace(s.charAt(--last))) ;

    return last == 0 ? "" : s.substring(0, last + 1);
}
相关问题