首先,判断一个字符串中是否含有双字节字符:
1 String str = "test中文汉字";
2 String regEx = "[//u4e00-//u9fa5]";
3
4 /**
5 * 判断有没有中文
6 */
7 if (str.getBytes().length == str.length()) {
8 System.out.println("无汉字");
9 } else {
10 System.out.println("有汉字");
11 }
12
13 /**
14 * 如果有则打印出来
15 */
16 Pattern p = Pattern.compile(regEx);
17 Matcher m = p.matcher(str);
18 while (m.find()) {
19 System.out.print(m.group(0) + "");
20 }
其次,是关于昨天的面试题街区字符串的问题:
package core_java;
public class StringInter {
public static boolean vd(char c){
boolean isGB2312=false;
byte[] bytes=(""+c).getBytes();
if(bytes.length==2){
int[] ints=new int[2];
ints[0]=bytes[0]& 0xff;
ints[1]=bytes[1]& 0xff;
if(ints[0]>=0x81 && ints[0]<=0xFE && ints[1]>=0x40 && ints[1]<=0xFE){
isGB2312=true;
}
}
return isGB2312;
}
static String Interception(String ss, int nn) {
if( nn > (ss.length())) nn = (ss.length());
for(int i=0; i <= ss.length(); i++){
//System.out.print("now nn is " +nn + "\n");
if( nn <= 0 ) return ss;
char t = ss.charAt(i);
if(vd(t)) { //说明是汉字 nn减二
if(nn == 1) return ss;
System.out.print(t);
nn-=2;
}
else { // 非汉字,nn减一
System.out.print(t);
nn--;
}
}
return ss;
}
public static void main( String args[] ) {
String a = "aま哈abcdefg";
// length() = charAt(0..)
//asd我是System.out.print(a.length());
//Scanner in = new Scanner(System.in);
//String s = in.nextLine();
//int n = in.nextInt();
Interception(a, 2);
}
}