Complex string split in Java

Posted by c0mrade on Stack Overflow See other posts from Stack Overflow or by c0mrade
Published on 2010-06-09T20:40:04Z Indexed on 2010/06/09 21:02 UTC
Read the original article Hit count: 437

Filed under:
|
|

Consider the following String :

5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+

Here is how I want to split string, split it with + so I get this result :

myArray[0] = "5|12345|value1|value2|value3|value4";

myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4";

if string has doesn't contain char "?" split it with "|" and continue to part II, if string does contain "?" split it and for each part split it with "|" and continue to part II.

Here is part II :

myObject.setAttribute1(newString[0]);
...
myObject.setAttribute4(newString[3]);

Here what I've got so far :

private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";

public void mapObject(String input){

String[] myArray = null;

    if (input.contains("+")) {
        myArray = input.split("+");
    } else {
        myArray = new String[1];
        myArray[0] = input;
    }

    for (int i = 0; i < myArray.length; i++) {

        String[] secondaryArray = null;
        String[] myObjectAttribute = null;

        if (myArray[i].contains("?")) {
            secondaryArray = temporaryString.myArray[i].split("?");

            for (String string : secondaryArray) {
                myObjectAttribute = string.split("\\|");
            }
        } else {
            myObjectAttribute = myArray[i].toString().split("\\|");
        }

        myObject.setAttribute1(myObjectAttribute[0]);
        ...
        myObject.setAttribute4(myObjectAttribute[3]);
                    System.out.println(myObject.toString());
}

Problem :

When I split myArray, going trough for with myArray[0], everything set up nice as it should.

Then comes the myArray[1], its split into two parts then the second part overrides the value of the first(how do I know that?). I've overridden toString() method of myObject, when I finish I print the set values so I know that it overrides it, does anybody know how can I fix this?

© Stack Overflow or respective owner

Related posts about java

Related posts about string