Java 按照位元組來截取字串的代碼(不會出現半個漢字)_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

/*
 *    Copyright 2012-2013 The Haohui Network Corporation
 */
package com.haohui.common.utils;

/**
 * <pre>
 * 字串協助工具輔助
 * </pre>
 *
 * @project baidamei
 * @author cevencheng <cevencheng@gmail.com>
 * @create 2012-11-30 下午2:42:56
 */
public class StringTool {

 /**
  *<b>截取指定位元組長度的字串,不能返回半個漢字</b>
  * 例如:
  * 如果網頁最多能顯示17個漢字,那麼 length 則為 34
  * StringTool.getSubString(str, 34);
  *
  * @param str
  * @param length
  * @return
  */
 public static String getSubString(String str, int length) {
  int count = 0;
  int offset = 0;
  char[] c = str.toCharArray();
  for (int i = 0; i < c.length; i++) {
   if (c[i] > 256) {
    offset = 2;
    count += 2;
   } else {
    offset = 1;
    count++;
   }
   if (count == length) {
    return str.substring(0, i + 1);
   }
   if ((count == length + 1 && offset == 2)) {
    return str.substring(0, i);
   }
  }
  return "";
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.