![](/img/trans.png)
[英]How can I check if an array of strings is empty in MongoDB with java?
[英]how can i count repeated strings in Array in java?
我想計算在java中的字符串數組中重復多次的字符串。 一種方法是找到這樣的字符串
String[] Array=new String[10];
String find;
System.out.print("Enter Strings for Array: ");
for(int i=0;i<Array.length;i++ ) {
Array[i]=input.next();
}
System.out.print("Enter String to find");
find=input.next();
for(int i=0;i<Array.length;i++) {
if(find.equals(Array[i]) {
System.out.print("Found!");
else
System.out.print("Not Found!");
}
}
但我想通過循環搜索重復的字符串並自行查找重復的字符串,而無需從用戶那里獲取輸入以進行查找。
第一個問題,您的代碼無法編譯。 您為if
語句打開一個塊,但不要在else
語句之前關閉它。
根據您的帖子,您似乎想要數組中的單詞數。 但是,您的代碼表明您正在嘗試查找數組中是否存在字符串。 我猜是前者,然后繼續。 可以使用Map
在 O(n) 中完成,而不是 O(n*n) 方法。
String[] arr = {"ab","c","d","e","ab"};
Map<String, Integer> map = new HashMap<String, Integer>();
for(String word: arr) {
// if word is not in the map
if(!map.containsKey(word))
map.put(word, 0);
map.put(word, map.get(word) + 1);
}
for(String word: map.keySet())
System.out.println(word + " occurs " + map.get(word) + " times");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.