62,620
社区成员
发帖
与我相关
我的任务
分享


public static String getBytes(int count,String str){
byte[] bytes = str.getBytes();
String str1 = new String(bytes,0,count);
while(!str.contains(str1)){
str1 = new String(bytes,0,++count);
}
return str1;
}
getBytes2可能不是最优解但肯定是较优解了
不过这样只适合GBK等双字节编码,万一在默认是UTF-8编码的机器上以上代码就是错的
所以应该用getBytes("GBK")和new String(bytes, 0, i, "GBK")
public static String getBytes3(int count,String str){
byte[] bytes = str.getBytes();
int i = 0,ic = 0;
while(ic < count){
if(bytes[i] >= 0){
i++ ;
}else{
i += 2;
}
ic++;
}
return new String(bytes,0,i);
}
public class java {
public static String getBytes(int count,String str){
byte[] bytes = str.getBytes();
String str1 = new String(bytes,0,count);
while(!str.contains(str1)){
str1 = new String(bytes,0,++count);
}
return str1;
}
public static String getBytes2(int count,String str){
byte[] bytes = str.getBytes();
int i = 0;
while(i<count){
if(bytes[i] >= 0){
i++ ;
}else{
i += 2;
}
}
return new String(bytes,0,i);
}
public static void main(String[] args){
String s = "我叫ABC哈哈哈";
for(int i = 1 ;i<9;i++){
System.out.println(getBytes(i,s ));
}
for(int i = 1 ;i<9;i++){
System.out.println(getBytes2(i,s ));
}
}
}