4

I have this code:

String string = "_a_b___";
String[] parts = string.split("_");

The result is that variable parts has only three elements

parts[0] = ""
parts[1] = "a" 
parts[2] = "b"

This is weird, because there are five "_" chars, so after splitting there should be six elements, not only three of them.

I want

parts[0] = ""
parts[1] = "a"
parts[2] = "b"
parts[3] = ""
parts[4] = "" 
parts[5] = "" 

How to do that? Thank you very much!

3
  • 1
    Just curious, why would you want the last three empty strings? Commented Jun 4, 2017 at 16:55
  • Because sometime I split "_a_b___" and sometime "x_a_b_c_d_e". Then I use parts[5] and in the first case it throws ArrayIndexOutOfBoundsException. Commented Jun 4, 2017 at 17:03
  • Oh, when I split, I play with the data at hand. Meaning, instead of using part[5]. I would using parts.length in a loop and do things accordingly. Commented Jun 4, 2017 at 17:07

2 Answers 2

6

From Java documentation:-

Trailing empty strings are therefore not included in the resulting array.

Trysplit("_",6)

Sign up to request clarification or add additional context in comments.

3 Comments

i like your solution you have my +1 it is a little not complete check my solution above
Nice.! Good find.
@YCF_L: Agree your ans is complete and elegant!
4

The solution of @Zakir is correct, i would add another information to use it perfectly, to get what you want instead of using split("_", 6) you can generalize it and use :

String[] parts = string.split("_", string.replace("(?!_)", "").length());

Which can accept any length.

for _a_b___ you will get [, a, b, , , ]


Edit

Or like @Bill F mention in comment, you can also use String[] parts = string.split("_", -1); for any length as well. Java doc

4 Comments

correct me if I'm wrong but you can also use split("_", -1) for any length as well. JavaDocs
you read deep deep @BillF this is correct you can also use split("_", -1) can i use this in my answer ?
thak you @BillF for your new information i appreciate it :) you can check my answer, feel free to edit it
Thanks! Just trying to help :) learn something new everyday :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.