題目
Problem Description
統計給定文本文件中漢字的個數。
Input
輸入文件首先包含一個整數n,表示測試實例的個數,然後是n段文本。
Output
對於每一段文本,輸出其中的漢字的個數,每個測試實例的輸出佔一行。
[Hint:]從漢字機內碼的特點考慮~
Sample Input
2
WaHaHa! WaHaHa! 今年過節不說話要說只說普通話WaHaHa! WaHaHa!
馬上就要期末考試了Are you ready?
Sample Output
14
9
思路
思路
漢字機內碼在計算機的表達方式的描述是,使用二個字節,每個字節最高位一位爲1。計算機中, 補碼第一位是符號位, 1 表示爲負數,所以漢字機內碼的每個字節表示的十進制數都是負數,因爲漢字佔用兩個字節結果要除以2。
代碼
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=Integer.parseInt(sc.nextLine());//next()WA
//int n=sc.nextInt();
//sc.nextLine();
while(n-->0){
String s=sc.nextLine();
int num=0;
byte b[]=s.getBytes();//將字符串轉化爲字節數組
for(int i=0;i<b.length;i++)//i<s.length()會WA
if(b[i]<0)
num++;
System.out.println(num/2);
}
}
}
}