Bogdan Razvan
Bogdan Razvan

Reputation: 1714

How to read strings and numbers separated by space in Java?

I've been working on a project in Java and I need to read a text file that looks like this

1 1 'Who is Albert Einstein?' 'commander' 'physicist' 'doctor' 1 I need to take the values separately , for example id=1,type=1,question=Who is Albert Einstein,answer1=commander etc.

Is there some way I can separate them by space and keep the strings between apostrophes as a whole?

Upvotes: 1

Views: 199

Answers (2)

PlasmaPower
PlasmaPower

Reputation: 1878

This should work:

try {
    BufferedReader reader = new BufferedReader(new FileReader("the-file-name.txt"));
    ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
    String line = reader.readLine();
    while(line != null) {
        ArrayList<String> values = new ArrayList<String>();
        String curr = "";
        boolean quote = false;
        for(int pos = 0; pos < line.length(); pos++) {
            char c = line.charAt(pos);
            if(c == '\'') {
                quote = !quote;
            }
            else if(c == ' ' && !quote) {
                values.add(curr);
                curr = "";
            }
            else {
                curr += c;
            }
        }
        lines.add(values);
        line = reader.readLine();
    }
    reader.close();
    // Access the first value of the first line as an int
    System.out.println("The first value * 2 is " + (Integer.parseInt(lines.get(0).get(0)) * 2));

    // Access the third value of the first line as a string
    System.out.println("The third value is " + lines.get(0).get(2));
} catch (IOException e) {
    System.out.println("Error reading file: ");
    e.printStackTrace();
} catch (Exception e) {
    System.out.println("Error parsing file: ");
    e.printStackTrace();
}

Upvotes: 0

Tim B
Tim B

Reputation: 41178

This is hard to do as a standard string split will not understand not to split anything inside the quotes.

You could write your own manual split easily enough, loop through, flip an "inQuote" flag every time you find a quote. Split on spaces whenever you find a space and the flag is not set.

Upvotes: 1

Related Questions