汉字统计

统计给定文本文件中汉字的个数。
Input
输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。
Output
对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。 

[Hint:]从汉字机内码的特点考虑~ 

Sample Input
2
WaHaHa! WaHaHa! 今年过节不说话要说只说普通话WaHaHa! WaHaHa!
马上就要期末考试了Are you ready?
Sample Output
14

9

import java.util.*;

 public class Main{
    static Scanner sc=new Scanner(System.in);
    static boolean isUnicode(char c){
        if(c >= 0x0391 && c <= 0xFFE5)
            return true;
        return false;
    }
    public static void main(String args[]){  
        int n=sc.nextInt();
        String str=sc.nextLine();
        while(n-->0){
            str=sc.nextLine();
            char[] ch=str.toCharArray();
            int count=0;
            for(int i=0;i<ch.length;i++){
                if( isUnicode(ch[i]) )
                    count++;
            }
            System.out.println(count)

        }
    }
}

反思:其实只要确定汉字的ASCII码的范围就好了,汉字的范围是19968-40869,值得注意的是,在Java里面汉字的个数被当做1(实际上占两个字节),字符串里如果有双字节的字符java就把每个字符都按双字节编码,如果都是单字节的字符就按单字节编码 


在这里在附上另一种代码:


import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
    static Scanner in =new Scanner(System.in);
	public static void main(String[] args) {
		int k = in.nextInt();
		in.nextLine();
		while(k-->0){
		  String str = in.nextLine();
		  int count = 0;  
	        String reg = "[\\u4e00-\\u9fa5]";  
	        Pattern p = Pattern.compile(reg);  
	        Matcher m = p.matcher(str);  
	        while (m.find()) {  
	            for (int i = 0; i <= m.groupCount(); i++) {  
	                count = count + 1;  
	            }  
	        }  
	        System.out.println(count);
		}		
	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值