統計一段文字中數組、中文、英文字母、空格以及其餘特殊字符出現的次數
- package util;
-
-
- public class CountStr {
-
- public static void main(String[] args) {
-
-
-
- String str = " 展恆理財,2004年在北京成立,是國內最大的理財諮詢類機構之一。得到國家頒發的獨立基金銷售牌照.是2013年中國網球公開賽10大核心贊助商之一。 公司成立10年來,在爲客戶進行全面的家庭財務規劃方面積累了十分豐富的經驗。目前擁有中高端忠實客戶10000多名,配置客戶資金超過200億元,位列 行業排名前三強。";
-
- System.out.println("[總字符數1]:"+countSum(str));
- System.out.println("--------------------");
- System.out.println("[總字符數2]:"+countSum2(str));
- System.out.println("--------------------");
- System.out.println("[總字符數3]:"+str.length());
- }
-
- public static int countSum(String str) {
- int unicodeCount = 0;
- int szCount = 0;
- int zmCount = 0;
-
- for (int i = 0; i < str.length(); i++) {
-
- char c = str.charAt(i);
- if (c >= '0' && c <= '9') {
- szCount++;
- }else if((c >= 'a' && c<='z') || (c >= 'A' && c<='Z')){
- zmCount++;
- }else{
- unicodeCount++;
- }
- }
- System.out.println("Unicode:"+unicodeCount);
- System.out.println("數字:"+szCount);
- System.out.println("字母:"+zmCount);
- int sum=szCount+zmCount+unicodeCount;
- return sum;
- }
- public static int countSum2(String str) {
- int abccount = 0;
- int numcount = 0;
- int spacecount = 0;
- int othercount = 0;
- char[] b = str.toCharArray();
- for(int i = 0; i < b.length; i++){
- if(b[i]>='a'&&b[i]<='z'||b[i]>='A'&&b[i]<='Z'){
- abccount++;
- }else if(b[i]>='0'&&b[i]<='9'){
- numcount++;
- }else if(b[i]==' '){
- spacecount++;
- }else{
- othercount++;
- }
- }
- int sum=abccount+numcount+spacecount+othercount;
- System.out.println("字符串中含有的英文字母數爲:" + abccount);
- System.out.println("字符串中含有的數字數爲:" + numcount);
- System.out.println("字符串中含有的空格數爲:" + spacecount);
- System.out.println("字符串中含有的其餘字符爲:" + othercount);
- return sum;
- }
- }
歡迎關注本站公眾號,獲取更多信息