0

I need some help with a splitting a text file with java. I have a text file with around 2000 words, the text file is in the format as follows -

"A", "HELLO", "RANDOM", "WORD"... etc

My goal is to put these words into a string array. Using the scanner class I'm taking the text and creating a string, then trying to split and add to an array as follows.

Scanner input = new Scanner(file);

while(input.hasNext()){

   String temp = input.next();

   String[] wordArray = temp.split(",");
}

After added to the array, when I want to use or print each element, they are stored with the "" surrounding them. Instead of printing

A
HELLO
RANDOM

… etc they are printing

"A"
"HELLO"
"RANDOM"

So my question is how can I get rid of these regular expressions and split the text at each word so I'm left with no regular expressions?

Many Thanks

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

3 Answers3

0

Try this

        List<String> allMatches = new ArrayList<>();
        Scanner input = new Scanner(new File(FILE_PATH), StandardCharsets.UTF_8);
        while(input.hasNext()){
            String temp = input.next();
            Matcher m = Pattern.compile("\"(.*)\"").matcher(temp);
            while (m.find()) {
                allMatches.add(m.group(1));
            }
        }
        allMatches.forEach(System.out::println);
Falah H. Abbas
  • 512
  • 5
  • 11
0

Just in your case, when you have all values like this "A", "HELLO", "RANDOM", "WORD"... etc, where every value have delimiter ", ", you can use this temp.split("\", \""); and you don't need to use loop.

-1

Use this to replace all occurrences of " with an empty string.

wordArray[i].replaceAll("/"", "");

Perform this in a loop.

Night King
  • 455
  • 4
  • 12