【www.gdgbn.com--excel】

按字节截取字符串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");
}

本文来源:http://www.gdgbn.com/bangongshuma/26763/