java按照字节切割字符串,解决汉字的问题
編寫一個(gè)截取字符串的函數(shù),輸入為一個(gè)字符串,截取開始地址,截取字節(jié)數(shù),輸出為按字節(jié)截取的字符串。 但是要保證漢字不被截半個(gè),
如“我ABC”,0,4,應(yīng)該截為“我AB”,輸入“我ABC漢DEF”,1,4,應(yīng)該輸出為“ABC”而不是“ABC+漢的半個(gè)”。
import java.io.UnsupportedEncodingException;
public class SubStr {
public static String bSubString(String str,int be,int length) throws UnsupportedEncodingException{
byte[] bytes;
bytes=str.getBytes("Unicode");
int z=be=2*be+2;
int n=0,count=0;
for(;be<bytes.length&&n<length;n++,be++){
if(bytes[be]==0){
n--;
}
count++;
}
System.out.println(be+" "+count+" "+n);
if(count%2==1){
if(bytes[count-1]!=0){
count--;
}else if(bytes[count-1]==0){
count++;
}
}
return new String(bytes,z,count,"Unicode");
?
}
public static void main(String[] args) {
String str="中國(guó)abc";
try {
System.out.println(bSubString(str,0,5));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}?
}
轉(zhuǎn)載于:https://www.cnblogs.com/mengjingchuanshuo/p/7113069.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的java按照字节切割字符串,解决汉字的问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 稀缺:百分之二的选择
- 下一篇: UML类图与类的关系详解【转】