Okay, Now I am able to parse space which was my previous problem. Now my parser is almost ready but has a defect which I am unable to figure out.
I am able to retrieve D
This will transform your input to your desired output (save the classes in two different files)
Parser.java
public class Parser {
public static final String ELEMENT_DELIM_REGEX = "\\|";
public static void main(String[] args) {
String input = "A|1|2|3^4|";
String[] tokens = input.split(ELEMENT_DELIM_REGEX);
Element[] elements = new Element[tokens.length];
for (int i = 0; i < tokens.length; i++) {
elements[i] = new Element(i + 1, tokens[i]);
}
for (Element element : elements) {
System.out.println(element);
}
}
}
and
Element.java
public class Element {
public static final String SUB_ELEMENT_DELIM_REGEX = "\\^";
private int number;
private String[] content;
public Element(int number, String content) {
this.number = number;
this.content = content.split(SUB_ELEMENT_DELIM_REGEX);
}
@Override
public String toString() {
if (content.length == 1) {
return "Element " + number + "\t" + content[0];
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < content.length; i++) {
str.append("Element " + number + "." + (i+1) + "\t" + content[i] + "\n");
}
// Delete the last \n
str.replace(str.length() - 1, str.length(), "");
return str.toString();
}
}
Use method Sting.split()
. Think about all your delimiters and put they all as an argument to split. Be aware that split works with regex, so special characters like |
must be escaped. For example line:
String[] tokens = str.split("[\\s+\\|]");
should create expected tokens from your input.
Scanner() by default has space as delimeter. So if you do scanner.next() again then you will get the remaining input part, '4'.
You can set your own delimeter by using usedelimeter(String pattern)
api of Scanner class.