【程式7】題目:
輸入一行字元,分别統計出其中英文字母、空格、數字和其它字元的個數。
思路:逐個讀吧。
package org.sixlab.algorithm40;
import java.util.HashMap;
import java.util.Map;
public class CharacterNumber {
public static void main(String\[\] args) {
String testString="Hello World! Hello 123! >-
System.out.println(countNumber(testString));
}
private static Map countNumber(String input) {
int englishNumber = 0;
int numberNumber = 0;
int spaceNumber = 0;
int otherNumber = 0;
int length = input.length();
for (int i = 0; i < length; i++) {
char tempChar = input.charAt(i);
if (Character.isDigit(tempChar)) {
numberNumber++;
} else if (Character.isSpaceChar(tempChar)) {
spaceNumber++;
} else if (Character.isLetter(tempChar)) {
englishNumber++;
} else {
otherNumber++;
}
}
Map map = new HashMap<>();
map.put("english", englishNumber);
map.put("number", numberNumber);
map.put("space", spaceNumber);
map.put("other", otherNumber);
return map;
}
}