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 ?
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 ?
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).
String[] parts = str.split("\\s*-\\s*");
String a = parts[0];
String b = parts[1];
int idx = str.indexOf(" - ");
String a = str.substring(0, idx);
String b = str.substring(idx+3, str.length());
split()
is a bit more computation intensive than indexOf()
, but if you don't need to split billions of times per seconds, you don't care.
String s = "Key - Value";
String[] arr = s.split("-");
String a = arr[0].trim();
String b = arr[1].trim();
I like using StringUtils.substringBefore and StringUtils.substringAfter from the belowed Jakarta Commons Lang library.
As a little bit longer alternative:
String text = "Key - Value";
Pattern pairRegex = Pattern.compile("(.*) - (.*)");
Matcher matcher = pairRegex.matcher(text);
if (matcher.matches()) {
String a = matcher.group(1);
String b = matcher.group(2);
}