Unable to parse ^ character

前端 未结 3 976
情深已故
情深已故 2021-01-27 15:06

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

3条回答
  •  悲&欢浪女
    2021-01-27 15:48

    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();
        }
    }
    

提交回复
热议问题