代码精读(截止10.1)
------- android培训、java培训、期待与您交流! ----------
反射练习代码 private static void changeStringValue(Object obj) throws Exception { // TODO Auto-generated method stub Field[] fields=obj.getClass().getFields();//得到类的成员变量,不是对象的变量 for(Field field:fields){ if(field.getType()==String.class){//同一段字节码使用双等号 String oldValue=(String)field.get(obj);//获得对象的成员变量的值,这里 String newValue=oldValue.replace('a', 'b');//进行替换 field.set(obj, newValue); } } } ------------------------------------------------------------------------------------------------------ 这种问题使用二楼的比较assic码方式,效率最好。楼主也可以试试用正则表达式 字母 [a-zA-Z] 数字 [0-9] 其它字符[[^\\w]&&[^\\s]] 空白字符 \s 代码如下: public static void main(String[] args) { //使用正则表达式 String target = "a34cf &*Sf 3dc42cd@."; //记录字母的数量 int letterCount = 0; //记录数字的数量 int numberCount = 0; //记录空格的数量 int spaceCount = 0; //记录其它字符的数量 int otherCount = 0; char[] chars = target.toCharArray(); //外联一个String的引用 String temp = null; for (int i = 0;i < chars.length;i++) { temp = String.valueOf(chars[i]); //把第i个位置的字符,转为字符串 if (temp.matches("[a-zA-Z]")) { //匹配字母 letterCount++; } else if (temp.matches("[0-9]")) { //匹配数字 numberCount++; } else if (temp.matches("[[^\\w]&&[^\\s]]")) { //匹配其它字符,出去空白字符 otherCount++; } else if (temp.matches("\\s")){ //匹配空白字符 spaceCount++; } } System.out.println("源字符串: " + target); System.out.println("字母: " + letterCount + ",数字: " + numberCount + ",空格: " + spaceCount + ",其它字符: " + otherCount); } 复制代码 利用ASCII码判断。 A~Z 65~90 a~z 97~122 空格 32 0~9 48~57 剩下的是其他字符。 int letter = 0; int num = 0; int space = 0; int other = 0; for(int i=0; i<ch.length; i++) { if ((ch[i]>=65&&ch[i]<=90)||(ch[i]>=97&&ch[i]<=122)) letter ++; else if (ch[i] == 32) space ++; else if (ch[i]>=48&&ch[i]<=57) num ++; else other ++; }