-2

I have a string like this qs_slc_az1_slx10c_1uytr_11. I want to split in such a way so that I can get the key as qs_slc_az1 and value will be slx10c_1uytr_11. How can I split on the underscore which is in between?

String s = "qs_slc_az1_slx10c_1uytr_11";
flash
  • 1,455
  • 11
  • 61
  • 132
  • Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – SSP Sep 24 '19 at 18:04

2 Answers2

0

Use substring:

String s = "qs_slc_az1_slx10c_1uytr_11";
String first = s.substring(0, 10); // qs_slc_az1
String second = s.substring(11); // slx10c_1uytr_11

To make it a little more actionable, just realize that the number 10 is the index of the underscore you wanted to split on. So you can make this into a function like this:

public static Pair<String, String> splitAtIndex(String s, int index) {
    return new Pair<>(s.substring(0, index), s.substring(index + 1));
}
smac89
  • 39,374
  • 15
  • 132
  • 179
0

The key point here: you do that by clarifying your requirements.

You have to specify: how many underscore characters are valid? Always 5? Or 3,5,7? Or, even numbers? 4,6? When you clarified that, you can then "define" what "middle" means to you. How long are the other parts of the input strings!?

The rest is then straight forward, but depends on your exact requirements.

If "always 5", you could simply use indexOf() repeatedly to identify the third underscore, and then "substring" manually before/after that.

Alternatively, just split by "_", and then manually merge back those parts they should sit together because "not in the middle".

GhostCat
  • 137,827
  • 25
  • 176
  • 248