JAVA截取中英文混合字符串

##JAVA截取中英文混合字符串

import java.io.*;
class test  
{
	public static void main (String[] args) throws java.lang.Exception
	{
	    StringBuffer sb = new StringBuffer();
		String str = "m我abc你好";
		int index=3;  //定义截取的长度
		int charLength = 0; 
		int strLength = str.length();  //获取字符的长度
		for (int i = 0;i<strLength ;i++ ){
		    int asciiCode = str.codePointAt(i);
		    //将每个字符装换为ASCII编码
		    if (asciiCode >=0 && asciiCode<=255){
		    //判断ASCII编码的范围,就是判断是否为汉字
		        charLength+=1; //非汉字字符长度加1
		    } else{
		        charLength+=2;//汉字字符长度加2
		    }
		    if (charLength<=index) {
		        sb.append(str.charAt(i));//截取字符
		    }else{
		        break;
		    }
		   
		}
		 System.out.println(sb.toString()); 
	}
}

猜你喜欢

转载自blog.csdn.net/system_obj/article/details/50630212