问题:有这样一个字符串“汉ABC字DEF”,假设在GBK编码格式下,一个中文字符占2个字节,需求是截取前6个字符,也就是“汉ABC”,而不是“汉ABC”+半个“字”。
解决方案:
public class StringDemo
{
public static void main(String[] args)
{
//System.getProperties().list(System.out);
String str = "汉ABC字DEF";
int index = 6;
System.out.println(str.length());
System.out.println(str.getBytes().length);
System.out.println(getStr(str, index));
}
/**
* 截取字符串前n个字符(含有中文字符的也通用)
* GBK编码格式中文字符占2个字节,UTF-8编码格式中文字符占3个字节
* @param str
* @param index
* @return
*/
public static String getStr(String str, int index)
{
if (null == str)
{
return null;
}
int count = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++)
{
String s = String.valueOf(str.charAt(i));
int len = s.getBytes().length;
if (len == 1)
{
count++;
}
else
{
count+=len;
}
if (index < count)
{
break;
}
else
{
sb.append(s);
}
}
return sb.toString();
}
}