截取带有中文的字符串

public class GetString {
   public static String getString(String str,int 
      len) {
	     String temp = ""; // 存取截取字符串
	      int count = 0;
	     boolean flag = false; // 标记char状态
		byte[] b = str.getBytes();
		if (len > str.length()) {
			return str;
		}

		for (int i = 0; i < len; i++) {
			if (b[i] < 0 && !flag) {
				flag = true;
				count += 1;
			} else {
				count = i + 1;
				flag = false;
			}
			temp = str.substring(0, count);
		}
		System.out.println(str);// 原字符串
		System.out.println(temp);
		return temp;
	}

	public static void main(String[] args) {
		String str = "abc我中国sg们w";
		getString(str, 4);
	} 

你可能感兴趣的:(Java)