我有一个字符串,我只想截取前面固定长度的部分(一个汉字算两个长度,英文字母和字符只算一个),这个方法应该怎么写,谢谢了。

解决方案 »

  1.   


    public class StringLength {
    public static String intercept(String str, int count) {
    if(str==null || str.trim().length()==0){
    return "";
    }
    byte[] temp = str.getBytes();
    if(count>=temp.length){
    return str;
    }
    byte[] byteArray = new byte[count-3];
    int ii = 0;
    for (int i = 0; i < count-3; i++) {
    byteArray[i] = temp[i]; if (temp[i] < 0) {
    ii++;
    }
    }
    if (ii % 2 == 1) {
    byteArray[count - 4] = ' ';
    }
    return new String(byteArray).trim() + "...";
    }
    }
      

  2.   

    感谢rumlee,这个方法果然好用。
      

  3.   

     byte[] byteArray = new byte[count-3];
    1楼朋友这里count如果<3会有异常的.
      

  4.   


    package selfimpr.oa.web;import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test4 { /**
     * @param args
     */
    public static void main(String[] args) {
    String str = "张三李e李";
    int count = 3;
    System.err.println(intercept(str, count, false));
    } /**
     * 截取字符串
     * @param str 要截取的目标字符串
     * @param count 要截取的长度
     * @param isShed 当截取的末尾是汉字的一个字节时, 是否舍去这一位. true表示舍去末尾位, false表示多补一位.
     * @return
     */
    public static String intercept(String str, int count, boolean isShed) {
    StringBuilder result = new StringBuilder();
    Pattern p1 = Pattern.compile(".");
    Matcher m1 = p1.matcher(str);
    int temp = count - (isShed ? 1 : 0);
    //int temp = count - 1; 此时最后一位所在为汉字, 导致要截断汉字时, 舍去最后一位.
    //int temp = count; 此时最后一位所在为汉字, 导致要截断汉字时, 多取一位, 得到一个整字.
    while(m1.find() && temp > 0) {
    result.append(m1.group());
    temp -= m1.group().getBytes().length;
    }
    return result.toString();
    }}