取指定长度的字符串(双字节算2)
代码
package com;
import java.util.Date;
public class StrFun {
public static void main(String[] args) {
String source = "123《中国》按时打发按时打发撒地方啊飒飒asdfasdfasd的法师打发似的<发(生的发生)地方按时打发是asdfasdfas";
int length = 10;
Date dt1 = new Date();
String temp = null;
for(int i = 0; i < 1000; i ++) {
temp = StrFun.omitString(source, length);
}
Date dt2 = new Date();
long ts = dt2.getTime() - dt1.getTime();
System.out.println(ts);
System.out.println(temp);
}
// 获取指定长度的字符串
public static String omitString(String string, int length) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
if (Integer.toHexString(string.charAt(i)).length() == 4) {
count += 2;
} else {
count++;
}
}
StringBuffer sb = new StringBuffer();
if (count > length) {
count = 0;
for (int i = 0; i < string.length(); i++) {
char temp = string.charAt(i);
if (Integer.toHexString(temp).length() == 4) {
count += 2;
} else {
count++;
}
if (count < length) {
sb.append(temp);
}
if (count == length) {
sb.append(temp);
break;
}
if (count > length) {
sb.append(" ");
break;
}
}
sb.append("");
} else {
sb.append(string);
}
return sb.toString();
}
}
import java.util.Date;
public class StrFun {
public static void main(String[] args) {
String source = "123《中国》按时打发按时打发撒地方啊飒飒asdfasdfasd的法师打发似的<发(生的发生)地方按时打发是asdfasdfas";
int length = 10;
Date dt1 = new Date();
String temp = null;
for(int i = 0; i < 1000; i ++) {
temp = StrFun.omitString(source, length);
}
Date dt2 = new Date();
long ts = dt2.getTime() - dt1.getTime();
System.out.println(ts);
System.out.println(temp);
}
// 获取指定长度的字符串
public static String omitString(String string, int length) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
if (Integer.toHexString(string.charAt(i)).length() == 4) {
count += 2;
} else {
count++;
}
}
StringBuffer sb = new StringBuffer();
if (count > length) {
count = 0;
for (int i = 0; i < string.length(); i++) {
char temp = string.charAt(i);
if (Integer.toHexString(temp).length() == 4) {
count += 2;
} else {
count++;
}
if (count < length) {
sb.append(temp);
}
if (count == length) {
sb.append(temp);
break;
}
if (count > length) {
sb.append(" ");
break;
}
}
sb.append("");
} else {
sb.append(string);
}
return sb.toString();
}
}