0

I am in need of some ideas. I have a file with some information like this:

AAA222BBB% CC333DDDD% EEEE444FF%

The '%' sign is like an indicator of "end of line"

I would like to read every line, and then parse it to fit a certain format (4 letters, 3 digits and 4 letters again) - So if it looks like the above, it should insert a special sign or whitespace to fill, like this:

AAA-222BBB-% CC--333DDDD% EEEE444FF--%

My first and immediate idea was to read every line as a string. And then some huge if-statement saying something like

For each line:
{
    if (first symbol !abc...xyz) {
        insert -
    }

    if (second symbol !abc...xyz) {
        insert -
    }
}

However, I am sure there must be a more elegant and effective way, do to a real parsing of the text, but I'm not sure how. So if anyone has a good idea please enlighten me :-)

Best

Niklas
  • 121
  • 1
  • 10
  • For File reading line by line you can use the java.util.Scanner ref:https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html. It has a method called "nextLine()" – Naga Srinu Kapusetti Sep 01 '16 at 17:26
  • 1
    Does input contain `%` or did you use it to show where lines should end? If it is second case did you use it because you don't know how to break lines in Stack Overflow editor? – Pshemo Sep 01 '16 at 17:28

1 Answers1

1

My first advice is to read this other post (nice explanation of scanner and regex): How do I use a delimiter in Java Scanner?

Then my solution (sure it is the the cleverest, but it should work)

For each line:
{
    Scanner scan = new Scanner(line);
    scan.useDelimiter(Pattern.compile("[0-9]"));
    String first = scan.next();

    scan.useDelimiter(Pattern.compile("[A-Z]"));
    String second = scan.next();

    scan.useDelimiter(Pattern.compile("[0-9]"));
    String third = scan.next();

    scan.close();

    System.out.println(addMissingNumber(first, 4) + addMissingNumber(second, 3) + addMissingNumber(third, 4));
}

 //For each missing char add "-"
 private static String addMissingNumber(String word, int size) {
    while (word.length() < size) {
        word = word.concat("-");
    }
    return word;
 }

The output: "AAA-222BBB-"

Community
  • 1
  • 1
Sergio F
  • 26
  • 4