题解 | #统计字符#
统计字符
http://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
// Use regex to judge if the character is letter digigt or another
java.lang.String regexLetter = "[a-zA-Z]";
Pattern rl = Pattern.compile(regexLetter);
java.lang.String regexDigit = "[0-9]";
Pattern rd = Pattern.compile(regexDigit);
java.lang.String regexWhiteSpace = "[\\s]";
Pattern rws = Pattern.compile(regexWhiteSpace);
char[] chars = sc.nextLine().toCharArray();
int isLetter = 0, isDigit = 0, isWhiteSpace = 0, isAnother = 0;
for(int i = 0; i < chars.length; i++) {
if(rl.matcher(Character.toString(chars[i])).matches()) {
isLetter++;
} else if(rd.matcher(Character.toString(chars[i])).matches()) {
isDigit++;
} else if (rws.matcher(Character.toString(chars[i])).matches()) {
isWhiteSpace++;
} else {
isAnother++;
}
}
System.out.println(isLetter);
System.out.println(isWhiteSpace);
System.out.println(isDigit);
System.out.println(isAnother);
}
}
}