Java 打印一个字符串的所有独特的词

Java 打印一个字符串的所有独特的词

编写一个函数,将一个字符串作为参数,并打印其中所有独特的单词。

例子

输入 : Java is great. Grails is also great
输出: Java
Grails
also

建议。请先在 {IDE} 上尝试你的方法,然后再继续解决。

方法:

我们的想法是使用地图来跟踪已经出现的单词。但首先,我们必须从一个字符串中提取所有的单词,因为一个字符串可能包含许多带有标点符号的句子。

关于从一个字符串中提取单词,请参阅从一个字符串中提取每个单词。

Python 我们的想法是使用一个字典来计算每个单词的数量。但首先,我们必须从一个字符串中提取所有的词,因为一个字符串可能包含标点符号。这是用regex或正则表达式完成的。字典中计数为1的单词是唯一的单词。

// Java program to print unique words
// from a string
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Test
{
    // Prints unique words in a string
    static void printUniquedWords(String str)
    {
        // Extracting words from string
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(str);
         
        // Map to store count of a word
        HashMap<String, Integer> hm = new HashMap<>();
         
        // if a word found
        while (m.find())
        {
            String word = m.group();
             
            // If this is first occurrence of word
            if(!hm.containsKey(word))
                hm.put(word, 1);
            else
                // increment counter of word
                hm.put(word, hm.get(word) + 1);
             
        }
         
        // Traverse map and print all words whose count
        // is  1
        Set<String> s = hm.keySet();
        Iterator<String> itr = s.iterator();
 
        while(itr.hasNext())
        {
            String w = itr.next();
             
            if (hm.get(w) == 1)
                System.out.println(w);
        }   
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "Java is great. Grails is also great";
        printUniquedWords(str);
    }
}
# Python program to print unique word
# in a string.
# Using re (Regular Expression module)
# It is used here to match a pattern
# in the given string
import re
 
# Declare a dictionary
dict = {}
 
# Method to check whether the word
# exists in dictionary or not
def uniqueWord(Word):
 
    if Word in dict:
 
        # If the word exists in dictionary then
        # simply increase its count
        dict[words] += 1
 
    else:
 
        # If the word does not exists in
        # dictionary update the dictionary
        # and make its count 1
        dict.update({words: 1})
 
# Driver code
if __name__ == '__main__':
     
    string = "Java is great. Grails is also great"
     
    # re.split() method is used to split
    # all the words in a string separated
    # by non-alphanumeric characters (\W)
    ListOfWords = re.split("[\W]+", string)
 
    # Extract each word from ListOfWords
    # and pass it to the method uniqueWord()
    for words in ListOfWords:
        uniqueWord(words)
 
    # Iterate over dictionary if the value
    # of the key is 1, then print the element
    for elements in dict:
        if dict[elements] == 1:
            print(elements)

输出

Java
Grails
also

方法2:使用set()

方法

在这种方法中,我们以单个单词的集合形式存储字符串并打印单词。

下面是上述方法的实现。

# python program to print all
# the unique words in a string
# in python using set() method
# function to print unique words
 
 
def printWords(l):
     
    # for loop for iterating
    for i in l:
        print(i)
 
 
# Driver code
str = "geeks for geeks"
 
# storing string in the form of list of words
s = set(str.split(" "))
 
# passing list to print words function
printWords(s)

输出

geeks
for

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程