题目:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,
如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。三个方法第一在论坛上看到的,第二个自己写的,第三个也是博客上的。。。。
package org.net.zone;
import java.io.UnsupportedEncodingException;
public class GetByte {
/**
* @param args
*/
public static void main(String[] args) {
String s = "我是acf中d国人adfgdd123";
for (int i = 1; i <= s.getBytes().length; i++) {
System.out.printf("%2d=%s\n", i, getSubString1(s, i));
System.out.printf("%2d=%s\n", i, getSubString2(s, i));
System.out.printf("%2d=%s\n", i, subString(s,i));
System.out.printf("++++++++++++\n");
}
}
/**
* Method1:
* 1.This method I can not understand
* 2.没看懂……
*/
private static String getSubString1(String s, int n) {
int count = 0;
int offset = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] > 256) {
offset = 2;
count += 2;
}
else {
offset = 1;
count++;
}
if (count == n) {
return s.substring(0, i + 1);
}
if ((count == n + 1 && offset == 2)) {
return s.substring(0, i);
}
}
return "";
}
/**Method2:
* 截取的要点:
* 1.首先将字符串转换成字节数组,再将字节数组的每个元素拿出来,判断有无负数(一个汉字为两个负数),即有汉字
* 2.len:这个len是将字符串转换成字节数组的要截取的长度,
* 如"我ABC你"的字节数组长度为7(-50,-46,65,66,67,-60,-29),而截取的是6(-50,-46,65,66,67,-60),
* 3.对截取的字节数组(-50,-46,65,66,67,-60)统计负数的个数
* 4.String里的方法substring方法将双字节的汉字当成一个字节的字符(UCS2字符)处理了,而我们的字节数组一个函数
* 就是两个字节,所以要想用substring方法,还需要将负数的个数count除以二才可以
*
*/
private static String getSubString2(String s, int n) {
byte[] c=s.getBytes();
int count=0;
for(int i=0;i= strLen || len < 1){
return str;
}
int count = 0;
for(int i=0; i