for 循环打印下面这句话中字母数不大于6的单词 whatever is worth doing
whatever is worth doing is worth doing well . 展开
获得字符串中各字母出现的次数并判断小于6就输出
public static void getWord(String str) {
int notWord = 0;
int c = str.length();
String word = "";
String words = "";
for(int i=0; i<c; i++){
if(!(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') && !(str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) {
notWord++;
}else {
word += str.charAt(i);
}
}
Map <Character, Integer> hm = new HashMap<Character, Integer>();
for(int j=0; j<word.length(); j++) {
int wordCount = 0;
for(int i=0; i<word.length(); i++) {
if(word.charAt(j) == word.charAt(i)) {
wordCount++;
}
}
hm.put(word.charAt(j), wordCount);
}
Iterator it = hm.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
if(hm.get(key)<6){
System.out.println(key+ "(" + hm.get(key) + ")");
}
}
}
2.测试
public static void main(String[] args) {
getWord("Whatever is worth doing is worth dooooing well.");
}
(不知道为什么回答的时候没看到 代码 的选项 显得有点乱)