用Java从键盘上输入一段中文组成的字符串,统计其中汉字个数。用三种方法
时间: 2024-02-29 09:52:13 浏览: 58
好的,下面是三种不同的方法来统计中文字符串中的汉字数量。
## 方法1:通过正则表达式匹配汉字
```java
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入中文字符串:");
String input = scanner.nextLine();
// 使用正则表达式匹配汉字
Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
Matcher matcher = pattern.matcher(input);
// 统计汉字数量
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("汉字数量:" + count);
}
}
```
## 方法2:通过遍历字符串判断每个字符是否为汉字
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入中文字符串:");
String input = scanner.nextLine();
// 遍历字符串,判断每个字符是否为汉字
int count = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (isChinese(c)) {
count++;
}
}
System.out.println("汉字数量:" + count);
}
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
}
}
```
## 方法3:通过将字符串转化为字符数组,判断每个字符是否为汉字
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入中文字符串:");
String input = scanner.nextLine();
// 将字符串转化为字符数组,判断每个字符是否为汉字
int count = 0;
for (char c : input.toCharArray()) {
if (isChinese(c)) {
count++;
}
}
System.out.println("汉字数量:" + count);
}
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
}
}
```
以上三种方法都可以用来统计中文字符串的汉字数量,您可以根据自己的需求选择其中一种。
阅读全文