0

I am trying to parse a String into a few variables. The String could contain these 4 tokens: "name, size, age, gender" but they don't all have to be there. Examples of possible Strings.

Example 1. "name:T-rex;"
Example 2. "name:T-rex;size:8;"
Example 3. "name:T-rex;age:4;gender:female"

I tried to do this:

private String name;
private String size;
private String age;
private String gender;

private String parse(String data)
{
    String [] parts = data.split(";");

    name = parts[0];
    size = parts[1];
    age = parts[2];
    gender = parts[3];
}

But that only works if the String data contains all 4 tokens. How can I solve this problem? I really do need the 4 variables.

3
  • 2
    For each item in parts, split again on :. Commented Aug 27, 2018 at 18:24
  • Are you guaranteed they wont be mixed up? Commented Aug 27, 2018 at 18:24
  • @MitchelPaulin the order won't change, so name will always be first. However, none are required. You may get a data that is missing the size or the gender. Commented Aug 27, 2018 at 18:25

2 Answers 2

2

The best way is to parse the string into key/value pairs and then call a method that sets them by key:

/**
* Set field based on key/value pair
*/
private void setValue(String key, String value) {
    switch(key) {
    case "name": {
        this.name = value;
        break;
    }
    case "age" : {
        this.age = value;
        break;
    }
    //...
    }
}

And call it in a programmatic way:

String[] k = "name:T-rex;age:4;gender:female".split(";");
for(String pair: k) {
    String[] a = pair.split(":");
    setValue(a[0], a[1]);
}

This allows you to be flexible, even to allow some keys to be missing.

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

2 Comments

split(":") instead of "="
@ernest_k Thank you!
0

Use the magic of hashmaps.

First, split the properties:

String[] parts = inStr.split( ";" );
List<String> properties = Arrays.asList(parts);

Then get name value pairs:

HashMap<String,String> map = new HashMap<String,String>();
Iterator<String> iter = properties.iterator();
for (String property : properties) {
    int colPosn = property.indexof(":");
    // check for error colPosn==-1
    map.put( property.substring(0, colPosn), property.substring(colPosn+1) );        
    }

Now you can access the properties out of order, and/or test for inclusion like tis:

if(map.containsKey("name") && map.containsKey("age")) {
    // do something
    String name = map.get("name");
    String age = map.get("age");
    ...

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.