我已經定義了一個函式 printWordsOccurence(String str)。列印此文本中每個單詞重復多少次是作業:
文字:我很高興。我是一名醫生。我喜歡巧克力。
預期結果:
- [3] 我
- [2] 上午
- [1] 開心。
- [1] 一個
- [1] 醫生。
- [1] 喜歡
- [1] 巧克力。
這是我的代碼:
public static void printWordsOccurence(String str) {
String[] words = str.split(" ");
int counter = 0;
for (int i = 0; i < words.length; i ) {
for (int j = 0; j < words.length; j ) {
if (words[i].equals(words[j])) {
counter ;
}
}
System.out.println(counter " " words[i]);
counter=0;
}
}
我無法阻止字串重復。任何建議或提示都會非常有幫助
uj5u.com熱心網友回復:
您需要做的是不要處理您已經看過的單詞。因此,當outer loop看到一個時,familiar它需要跳過它。
最簡單的方法是使用集合或地圖。但是還有另一種使用大多數現有代碼的替代方法。
- 只需在遇到某個字串時替換該單詞即可。
- 然后,如果外回圈再次遇到該字串,則忽略它。
public static void printWordsOccurence(String str) {
String[] words = str.split(" ");
// the marker which replaces the word when found.
String seen = "#";
for (int i = 0; i < words.length; i ) {
// if the word equals the marker, continue continue on
// to the next word in this loop
if (words[i].equals(seen)) {
continue;
}
int counter = 0;
// save the word since it may change when found
String find = words[i];
for (int j = 0; j < words.length; j ) {
if (find.equals(words[j])) {
// replace the word with the substitute
words[j] = seen;
counter ;
}
}
System.out.println(counter " " find);
}
}
印刷
3 I
2 am
1 happy.
1 a
1 doctor.
1 like
1 chocolate.
您可能想要修改單詞以消除任何揮之不去的標點符號。
uj5u.com熱心網友回復:
您正在外回圈中列印訊息,它將為每個單詞執行!請嘗試使用地圖。這里我不使用流。剛剛使用 Java 7 的方式。`
public static void printWordsOccurence(String str) {
String[] words = str.split(" ");
Map<String, Integer> res = new LinkedHashMap<>();
for (String w : words) {
if (res.containsKey(w)) {
res.put(w, res.get(w) 1);
} else {
res.put(w, 1);
}
}
for (String w: res.keySet()) {
System.out.println("[" res.get(w) "]" w);
}
}
`
uj5u.com熱心網友回復:
private static void printWordOccurance(String sentence) {
Map<String, Integer> countMap = new HashMap<>();
Arrays.stream(sentence.split("\\s ")).forEach(word -> countMap.compute(word, (k, v) -> v == null ? 1 : v 1));
System.out.println(countMap);
}
uj5u.com熱心網友回復:
嘗試這個。
public static void printWordsOccurence(String str) {
Arrays.stream(str.split("[\\s.] "))
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()))
.entrySet().forEach(e ->
System.out.println("[" e.getValue() "] " e.getKey()));
}
public static void main(String[] args) {
String str = "I am happy. I am a doctor. I like chocolate.";
printWordsOccurence(str);
}
輸出:
[3] I
[2] am
[1] happy
[1] a
[1] doctor
[1] like
[1] chocolate
或者
public static void printWordsOccurence(String str) {
Map<String, Integer> counter = new LinkedHashMap<>();
for (String word : str.split("[\\s.] "))
counter.merge(word, 1, Integer::sum);
for (Entry<String, Integer> e : counter.entrySet())
System.out.println("[" e.getValue() "] " e.getKey());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/350600.html
上一篇:java-如何檢查Java中的兩個引數是其中之一為空還是兩者都為空
下一篇:很難找到程式集中的字符數
