[英]How to compare between an array string element and set string element in java
Here I need to compare the elements present in a Set with the elements in an array.在这里,我需要将 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);
}
}`
The logic behind my code is: I received an input sentence and I converted it into lowercase.我的代码背后的逻辑是:我收到一个输入句子并将其转换为小写。 Then I split each word based on some characters as mentioned in the code and store each splitted word to array.
然后我根据代码中提到的一些字符拆分每个单词,并将每个拆分的单词存储到数组中。 Now I convert it into a set.
现在我把它转换成一个集合。 Now I need to count the frequency of each element in the set with repsect to the array.
现在我需要用对数组的表示来计算集合中每个元素的频率。
For example If I give input as "hi hi hi hello" I would get Number of words 4 hi:3 hello:1例如,如果我输入“hi hi hi hello”,我会得到 Number of words 4 hi:3 hello:1
So please help me to solve this.所以请帮我解决这个问题。
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);
}
Use the below code count the frequency of each element.使用下面的代码计算每个元素的频率。
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.