Java获取字符串里的汉字

本文提供了一种方法来从给定的字符串中筛选并获取所有汉字字符,以及如何提取前200个汉字。通过字符转换和字节长度判断,实现对文本内容的精确提取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取字符串中的所有汉字:

public static String getChinese(String str)
  {
      char[] chars=str.toCharArray();
      String chinese = "";
      for(int i=0;i<chars.length;i++){
             byte[] bytes=(""+chars[i]).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){
                  chinese +=  chars[i];
                 }
             }
      }
   return chinese;
  }

获取字符串中的前200个汉字

public static String getChinese(String str)
  {
      char[] chars=str.toCharArray();
      String chinese = "";
      for(int i=0;i<chars.length;i++){
             byte[] bytes=(""+chars[i]).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){
                  chinese +=  chars[i];
                 }
             }
             if(chinese.length()>200){
              break;
             }
      }
   return chinese;
  }