JAVA 統計字串中的漢字、英文字母、數字、其他符號的數量
阿新 • • 發佈:2018-12-30
</pre><pre name="code" class="html">去除字串的空格方法: 1. String.trim() trim()是去掉首尾空格 2.str.replace(" ", ""); 去掉所有空格,包括首尾、中間 String str = " hell world "; String str2 = str.replaceAll(" ", ""); System.out.println(str2); 3.或者replaceAll(" +",""); 去掉所有空格 4.str = .replaceAll("\\s*", ""); 可以替換大部分空白字元, 不限於空格 \s 可以匹配空格、製表符、換頁符等空白字元的其中任意一個
public static int getContentWordCount(String content){ content = content.replaceAll("\\s", "");//可以替換大部分空白字元,不限於空格 int hzCount = 0;//漢字數量 int szCount = 0;//數字數量 int zmCount = 0;//字母數量 int fhCount = 0;//標點符號數量 for(int i = 0;i < content.length();i++){ char c = content.charAt(i); if(c >= '0' && c <= '9'){ szCount++; }else if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){ zmCount++; }else if(Character.toString(c).matches("[\\u4E00-\\u9FA5]+")){ hzCount++; }else{ fhCount++; } } return hzCount+szCount+zmCount; }