Reputation: 2418
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.
Upvotes: 0
Views: 99
Reputation: 913
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");
...
Upvotes: 0
Reputation: 45339
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.
Upvotes: 2