Reputation: 7924
I've a string which contains following data:
user_id:16|login_id:6|pass_id:6|email:[email protected]|product_id:|name:Mike|created_date:20120101:12:22|address:US
How can I get the each field in Java?
I can use split but then later how would I get the colon separator? Also, how can I handle created_date as it has 2 colons, so I won't be able to separate by colon.
Also, note that product_id is empty.
Any sample in Java 1.6 is much appreciated.
Thanks!
Upvotes: 0
Views: 94
Reputation: 1066
Look you can use this technique (delimiting strings) only when you are pretty sure of the fact that the data you are getting from the source will always strictly follow this standard.
Find some other technique otherwise, most preferably XML or JSON.
Upvotes: 0
Reputation: 59694
First solution comes in my mind is: (Not sure this is efficient)
|
Example:
String str = "user_id:16|login_id:6|pass_id:6|email:[email protected]|product_id:|name:Mike|created_date:20120101:12:22|address:US";
String[] strArr = str.split("\\|");
for (String string : strArr) {
System.out.println("First part: " + string.substring(0, string.indexOf(":")));
System.out.println("Second part: " + string.substring(string.indexOf(":")+1));
System.out.println();
}
Assumption: No :
comes in name(first part). ie first :
will always come after the complete name(first part) and then value(second part).
Upvotes: 4