简体   繁体   English

如何检查字符串中的相同单词?

[英]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时会执行此操作)。

See here for details: HashSet 详细信息请参见此处: HashSet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查给定的字符串是否为单词 - How to check whether given string is a word 如何检查一个字符串是否包含单词而不是实际的字符串 - How to check if a String contains a word and not an actual piece of String 如何检查文件中的单词是否存在 - How to check a word in a file there is or not the word 如何检查第一个字符串中的单词是否可以重新排列以拼写第二个字符串中的单词? - How to check if the word in the first string can be re-arranged to spell the word in the second string? 如何检查两个字符串数组是否相同 - How to Check If Two String Arrays are The Same 如何检查字符串中的字符是否与前一个字符相同? - how to check if the char in a string is the same as the previous char? 如何检查由7个随机字母组成的字符串是否可以形成文件中存在的单词 - How to check if a string of 7 random letters can form a word that exists in a file 如何检查ArrayList中的项目 <String> 不包含某个单词? - How to check if an item in an ArrayList<String> does not contain a certain word? 如何检查数组是否包含字符串中的特定单词并获取它? - How to check if an Array contains a particular word in a String and get it? 正则表达式很慢,如何检查一个字符串是否只有单词字符快? - regex is very slow, how to check if a string is only with word chars fast?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM