判断字符串有几个汉字,分别在什么位置?
String s = "我的的01天啊2345我的啊的678901天23456789啊1";
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(s.substring(0, 30));
int count = 0;
while (matcher.find()) {
count++;
System.out.println(" 所在位置:");
}
System.out.println(" 汉字个数:"+count);
谢谢大侠啊
[解决办法]
- Java code
public static void main(String[] args) { String s = "我的的01天啊2345我的啊的678901天23456789啊1"; int count = 0; for(int i = 0; i < s.length(); i++){ Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(s.substring(i, i + 1)); if(matcher.matches()){ System.out.println(" 所在位置:" + i); count++; }else{ System.out.println(i + " 位置上不是汉字"); } } System.out.println(" 汉字个数:"+count); }
[解决办法]
- Java code
while (matcher.find()) { count++; System.out.println(" 所在位置:" + matcher.start()); }
[解决办法]
[解决办法]
两种方式任选一种
[解决办法]
另外,第2行语句有问题,所以找出来的汉字少了一个:
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(s);
[解决办法]
偷懒的做法
- Java code
String s = "我的的01天啊2345我的啊的678901天23456789啊1";System.out.printf("汉字个数:%s\n", s.getBytes().length - s.length());for (int i=0; i<s.length(); i++) { String sub = s.substring(i, i+1); if (sub.getBytes().length > sub.length()) { System.out.printf("汉字:%s, 位置:%d\n", sub, i); }}