Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Split in Java and substring the result [duplicate]

Possible Duplicate:
string split in java

I have this Key - Value , and I want to separate them from each other and get return like below:

String a = "Key"
String b = "Value"

so whats the easiest way to do it ?

like image 973
Peril Avatar asked Sep 26 '11 13:09

Peril


People also ask

What does split \\ s+ do in Java?

split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.


1 Answers

String[] tok = "Key - Value".split(" - ", 2);
// TODO: check that tok.length==2 (if it isn't, the input string was malformed)
String a = tok[0];
String b = tok[1];

The " - " is a regular expression; it can be tweaked if you need to be more flexible about what constitutes a valid separator (e.g. to make the spaces optional, or to allow multiple consecutive spaces).

like image 90
NPE Avatar answered Sep 28 '22 06:09

NPE