2

I want to split each line into two separate strings when reading through the txt file I'm using and later store them in a HashMap. But right now I can't seem to read through the file properly. This is what a small part of my file looks like:

....
CPI       Clock Per Instruction 
CPI       Common Programming Interface [IBM]
.CPI      Code Page Information (file name extension) [MS-DOS]
CPI-C     Common Programming Interface for Communications [IBM]
CPIO      Copy In and Out [Unix]
....

And this is what my code looks like:

    try {
        BufferedReader br = new BufferedReader(new FileReader("akronymer.txt"));
        String line;

        String akronym;
        String betydning;
        while((line = br.readLine()) != null) {
            String[] linje = line.split("\\s+");

            akronym = linje[0];
            betydning = linje[1];

            System.out.println(akronym + " || " + betydning);
        }
    } catch(Exception e) {
        System.out.println("Feilen som ble fanget opp: " + e);
    }

What I want is to store the acronym in one String and the definition in another String

8
  • So what is stopping you? Commented Nov 26, 2013 at 19:54
  • 1
    @PeterLawrey I think, The way OP is splitting the String on whitespaces. Commented Nov 26, 2013 at 19:55
  • @Smit That looks fine to me. Commented Nov 26, 2013 at 19:56
  • 1
    @user3037979 That is because you are splitting by spaces. If you want to stop once you reach the second string, add 2 as a maximum strings argument. Commented Nov 26, 2013 at 19:57
  • 1
    @PeterLawrey That was my point you just mentioned in your previous comment. Commented Nov 26, 2013 at 19:59

2 Answers 2

4

The problem is that whitespace in the definition is interpreted as additional fields. You're getting only the first word of the definition in linje[1] because the other words are in other array elements:

["CPI", "Clock", "Per", "Instruction"]

Supply a limit parameter in the two-arg overload of split, to stop at 2 fields:

String[] linje = line.split("\\s+", 2);

E.g. linje[0] will be CPI and linje[1] will be Clock Per Instruction.

Sign up to request clarification or add additional context in comments.

Comments

4

If you want to limit your split to only two parts then use split("\\s+", 2). Now you are splitting your line on every whitespace, so every word is stored in different position.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.