[英]How to check for the same word in a string?
My code takes a String input, separates them and locates the ones with a specific letter in them, then prints them. 我的代码接受一个String输入,将它们分开,并在其中找到带有特定字母的字母,然后打印它们。 Now, i want to make sure the same word only prints once. 现在,我想确保同一单词只打印一次。 For instance, if the input was " she looks nice, she is kind." 例如,如果输入的内容是“她看起来不错,她就很友善”。 then the output would be "she \\n nice" This is my current code: 那么输出将是“她\\ n好”这是我当前的代码:
Scanner kybd = new Scanner(System.in);
String s = kybd.nextLine();
String[] arr = s.split(" ");
for ( String ss : arr) {
String []ary = {ss};
for(int i = 0; i < ary.length; i++){
int numindex = ss.indexOf("e");
int numindex2 = ss.indexOf("E");
if (numindex != -1){
System.out.println(ary[i]);
}
else if(numindex2 != -1){
System.out.println(ary[i]);
}
}
}
Any suggestions on how to do this would be appreciated. 任何建议如何做到这一点将不胜感激。
Add your words to a HashSet<String>
. 将您的单词添加到HashSet<String>
。
Then loop through this HashSet and print out the words. 然后遍历此HashSet并打印出单词。
Even if there are duplicates (while you extract them), 即使有重复项(提取时),
they will be printed out once. 它们将被打印一次。
The HashSet will get rid of the duplicates for you HashSet将为您消除重复项
(it will do that while you insert them into the HashSet). (在将它们插入HashSet时会执行此操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.