按位元組截取字串java代碼

來源:互聯網
上載者:User

按位元組截取字串java代碼
本文章提供三款java截取字串函數,他們可以按位元組不來取截取字串長度的代碼,很方便執行個體。
* 取字串的前tocount個字元
*
* @param str 被處理字串
* @param tocount 截取長度
* @param more 尾碼字串
* @version 2004.11.24
* @author zhulx
* @return string
*/

public static string substring(string str, int tocount,string more)
{
int reint = 0;
string restr = "";
if (str == null)
return "";
char[] tempchar = str.tochararray();
for (int kk = 0; (kk < tempchar.length && tocount > reint); kk++) {
string s1 = str.valueof(tempchar[kk]);
byte[] b = s1.getbytes();
reint += b.length;
restr += tempchar[kk];
}
if (tocount == reint || (tocount == reint - 1))
restr += more;
return restr;
}


//截取字串方法二

import java.util.*;

public class study {
 public static void main(string[] args) {
  stringbuilder sb = new stringbuilder();
  system.out.println(system.currenttimemillis());
  for(int i = 0; i < 1000000; i++){
   sb.append("1234567890");
  }
  system.out.println(system.currenttimemillis());
  string str = sb.tostring();
  random rand = new random();
  for(int i = 0; i < 1000000; i++){
   int beg = rand.nextint(5000000);
   int end = rand.nextint(5000000)+beg;
   str.substring(beg, end);
  }
  system.out.println(system.currenttimemillis());
 }
}

//方法三

public static string substring(string s , int length) throws exception
{
byte[] bytes = s.getbytes("unicode");
int n = 0; // 表示當前的位元組數
int i = 2; // 要截取的位元組數,從第3個位元組開始

for (; i < bytes.length && n < length; i++){
// 奇數位置,如3、5、7等,為ucs2編碼中兩個位元組的第二個位元組
if (i % 2 == 1){
n++; // 在ucs2第二個位元組時n加1
}
else{
// 當ucs2編碼的第一個位元組不等於0時,該ucs2字元為漢字,一個漢字算兩個位元組
if (bytes[i] != 0){
n++;
}
}
}
// 如果i為奇數時,處理成偶數
if (i % 2 == 1)
{
// 該ucs2字元是漢字時,去掉這個截一半的漢字
if (bytes[i - 1] != 0){
i = i - 1;
}
else{// 該ucs2字元是字母或數字,則保留該字元
i = i + 1;
}
}
return new string(bytes, 0, i, "unicode");
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.