简体   繁体   中英

Read File and find unique words

I want to read a file and get the the number of unique words in it. So far I am able to read the file line by line (readline), store it in an arraylist and then manipulate the string.

My input will look like :

(OR (OR tv party) (study)) (=> exam (NOT (OR tv party)))

Basically, I am trying to convert each line from prefix to infix and I need to find out all the diff variables involved in the input file (like tv, party etc) so that I can construct a truth table and test the cases.

Currently I am manipulating all the Strings in the array list. Is there a better way yo do this?

If you want to find the variables, try:

String line = "(OR (OR tv party) (study)) (=> exam (NOT (OR tv party)))";
Scanner sc = new Scanner(line);
sc.useDelimiter("[^a-z]");
Set<String> set = new TreeSet<String>();
while(sc.hasNext()) {
    String word = sc.next();
    if (!word.isEmpty()) {
        set.add(word);
    }
}
System.out.println(set);

This prints:

[exam, party, study, tv]

Split lines and store the words into Set . At the end you will get the unique words. If you want to know the words count too use map<String, Integer> where key (string) is the words and value (integer) is the counter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM