Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read one-line text file, split to array

I'm reading a long line of info from a text file that looks exactly like this:

Sebastien 5000\\Loic 5000\\Shubhashisshh 5000\\Thibaullt 5000\\Caroo 5000\\Blabla 5000\\Okayyy 5000\\SebCed 5000\\abusee 5000\\omg 5000\\

It's supposed to be high scores with the names of users. When I print out the line, it looks exactly like it should, but when I print out the array after using split("\\\\"), it looks like this:

[Sebastien 5000, , Loic 5000, , Shubhashisshh 5000, , Thibaullt 5000, , Caroo 5000, , Blabla 5000, , Okayyy 5000, , SebCed 5000, , abusee 5000, , omg 5000]

The problem is that Array[0] is fine but Array[1] is empty, as are Array[3], Array[5], etc.

Here is my code. What's wrong with it?

            BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(path));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    String line = null;
    try {
        line = in.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("LINE = "+line);

    String[] scores = line.split("\\\\");

    System.out.println("Mode = "+mode+Arrays.toString(scores));
like image 780
user1895293 Avatar asked Dec 11 '12 16:12

user1895293


2 Answers

That's because "\\\\" is being parsed as \\ and the split method uses a regular expression, so \\ is becoming \, then Sebastien 5000\\Loic 5000 will result in [Sebastien 5000,,Loic 5000]

Do this instead: "\\\\\\\\"

like image 110
José Roberto Araújo Júnior Avatar answered Oct 23 '22 22:10

José Roberto Araújo Júnior


Just for fun, aside José Roberto solution, you can also use some alternative expressions (and lots others):

Two consecutive backslashes (same that in José's, but using a quantifier):

String[] scores = line.split("\\\\{2}");

Two consecutive Non-Word Characters:

String[] scores = line.split("\\W{2}");

Two consecutive punctuation chars:

String[] scores = line.split("\\p{Punct}{2}");

All of them produce the required output.

For more info on Regular expressions in Java:

  • Class Pattern Javadoc
  • Java tutorial on Regular Expressions
like image 3
Tomas Narros Avatar answered Oct 23 '22 20:10

Tomas Narros