[英]How to compare between an array string element and set string element in java
在這里,我需要將 Set 中存在的元素與數組中的元素進行比較。
`System.out.println("Enter Student's Article");
sentence=sc.nextLine();
lowerCase(sentence);
String [] array=sentence.split("[ ,;:.?!]+");
System.out.println("Number of words "+array.length);
Set <String> set=new HashSet<>(Arrays.asList(array));
//System.out.println(set.size());
for(String str:set){
count=0;
for(int j=0;j<array.length;j++){
if(str==array[j])
count++;
System.out.println(count);
}
System.out.println(str+":"+count);
}
}`
我的代碼背后的邏輯是:我收到一個輸入句子並將其轉換為小寫。 然后我根據代碼中提到的一些字符拆分每個單詞,並將每個拆分的單詞存儲到數組中。 現在我把它轉換成一個集合。 現在我需要用對數組的表示來計算集合中每個元素的頻率。
例如,如果我輸入“hi hi hi hello”,我會得到 Number of words 4 hi:3 hello:1
所以請幫我解決這個問題。
Try the code below and compare the changes with your original code
Scanner sc=new Scanner(System.in);
String sentence=sc.nextLine();
sentence.toLowerCase();
String [] array=sentence.split("[ ,;:.?!]+");
System.out.println("Number of words "+array.length);
Set <String> set=new HashSet<>(Arrays.asList(array));
//System.out.println(set.size());
for(String str:set){
int count=0;
for(int j=0;j<array.length;j++){
if(str.equals(array[j]))
count++;
//System.out.println(count);
}
System.out.println(str+":"+count);
}
使用下面的代碼計算每個元素的頻率。
Map<String , Integer> dictionary=new HashMap<String,Integer>();
String myWords = "soon hi also soon job mother job also soon later";
myWords = myWords.toLowerCase();
String[] array=myWords.split("\\s+");
for(String s:array){
if(dictionary.containsKey(s))
dictionary.put(s, dictionary.get(s)+1);
else
dictionary.put(s, 1);
}
System.out.println("Number of words "+myWords.length());
for (String key : dictionary.keySet()) {
System.out.print(key +":"+ dictionary.get(key));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.