JAVA统计汉字、字符、空格、数字

来源:互联网 发布:手机网络动漫城 编辑:程序博客网 时间:2024/05/29 16:04
  //JAVA统计汉字、字符、空格、数字package com.javaio.test;

import java.io.UnsupportedEncodingException;

public class TestString {
 
 
 public static int countHanzi(String s)
 {
  int count=0;
  try {
   s=new String(s.getBytes(),"GBK");
   
   for(int i=0;i<s.length();i++)
   {
    char c=s.charAt(i);
    if(String.valueOf(c).getBytes().length>1)
    {
     count++;
    }
    
   }
   System.out.println(count);
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return count;
  
 }
 
   //统计字符、空格、数字
 public static void getCountqita(String a)
 {
  char ch;
  int konggesum=0;
  int charsum=0;
  int numbersum=0;
  for(int i=0;i<a.length();i++)
  {
   ch=a.charAt(i);
   if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z'))
   {
    charsum++;
   }
   if(ch>='0'&&ch<='9')
   {
    numbersum++;
   }
   if(ch==' ')
   {
    konggesum++;
   }
   
  }
  System.out.println("数字有几"+numbersum+"个,"+"字符有几"+charsum+"个,"+"空格有几"+konggesum+"个,");
     // if() 
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  TestString.countHanzi("d23董 利 刚 56ABCZ");
  TestString.getCountqita("d23董 利 刚 56ABCZ");
 }

}