按位元組截取字串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");
}