首页 > 代码库 > java每日小算法(7)

java每日小算法(7)

/*【程序7】
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
1.程序分析:利用while语句,条件为输入的字符不为‘\n‘.  */
package test;
import java.util.ArrayList;
import java.util.List;
public class test {
     public static List<Integer> countstr(String input) {
         List<Integer> result = new ArrayList<Integer>();
         int number = 0;
         int letter = 0;
         int blank = 0;
         int other = 0;
         for(int i = 0; i<input.length(); i++)
         {
             if(input.charAt(i)>=‘0‘ && input.charAt(i)<=‘9‘)
                 number++;
             else if(input.charAt(i)>=‘a‘ && input.charAt(i)<=‘z‘)
                 letter++;
             else if(input.charAt(i)>=‘A‘ && input.charAt(i)<=‘Z‘)
                 letter++;
             else if(input.charAt(i) == ‘ ‘)
                 blank++;
             else
                 other++;
         }
         result.add(number);
         result.add(letter);
         result.add(blank);
         result.add(other);
         return result;
     }
            
        
 public static void main(String[] args) {
     long a = System.currentTimeMillis();
     String input = "234jkadbnERFGfq3 98G45nr2EG49 r85^&ERweuf34jn#$%tq8 9wfXCVu34#$%nr818371!@#2";
    List<String> strname = new ArrayList<String>();
    strname.add("number");
    strname.add("letter");
    strname.add("blank");
    strname.add("other");
     for(int i = 0; i < countstr(input).size(); i++)
        System.out.println("The count of "+strname.get(i)+" in this string is "+countstr(input).get(i));
     System.out.println(System.currentTimeMillis() - a);
 }
}
The count of number in this string is 26
The count of letter in this string is 36
The count of blank in this string is 3
The count of other in this string is 11
3