10

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 ?

Community
  • 1
  • 1
Peril
  • 1,569
  • 6
  • 25
  • 42
  • 1
    Have you tried String.split(...) ? – Gandalf Sep 26 '11 at 13:51
  • 1
    I am a php developer so its kinda different , but now I know my mistake , it was using single quotation in the split method – Peril Sep 26 '11 at 13:54
  • 1
    @Salah Yahya: Next time, try to also mention what you already tried inside the question, that way it has more value for future visitors. I even encourage you rewriting this question so it indicates a bit more effort. – Steven Jeuris Sep 26 '11 at 13:58

7 Answers7

12
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).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
6
String[] parts = str.split("\\s*-\\s*");
String a = parts[0];
String b = parts[1];
AlexR
  • 114,158
  • 16
  • 130
  • 208
3
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.

Aurelien Ribon
  • 7,548
  • 3
  • 43
  • 54
2
String s = "Key - Value";
String[] arr = s.split("-");
String a = arr[0].trim();
String b = arr[1].trim();
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
2

I like using StringUtils.substringBefore and StringUtils.substringAfter from the belowed Jakarta Commons Lang library.

Ravi Wallau
  • 10,416
  • 2
  • 25
  • 34
1

something like

String[] parts = "Key - Value".split(" - ");
String a = parts[0];
String b = parts[1];
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
MarcoS
  • 13,386
  • 7
  • 42
  • 63
1

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);
    }
box
  • 3,156
  • 3
  • 26
  • 36