1

I have a string like

String myString = "hello world~~hello~~world"

I am using the split method like this

String[] temp = myString.split("~|~~|~~~");

I want the array temp to contain only the strings separated by ~, ~~ or ~~~.

However, the temp array thus created has length 5, the 2 additional 'strings' being empty strings.

I want it to ONLY contain my non-empty string. Please help. Thank you!

2
  • Please format your code with the corresponding markup for readability: stackoverflow.com/editing-help#code Commented Aug 30, 2013 at 9:53
  • Sorry, I will pay attention :) Commented Aug 30, 2013 at 10:01

3 Answers 3

8

You should use quantifier with your character:

String[] temp = myString.split("~+");

String#split() takes a regex. ~+ will match 1 or more ~, so it will split on ~, or ~~, or ~~~, and so on.

Also, if you just want to split on ~, ~~, or ~~~, then you can limit the repetition by using {m,n} quantifier, which matches a pattern from m to n times:

String[] temp = myString.split("~{1,3}");

When you split it the way you are doing, it will split a~~b twice on ~, and thus the middle element will be an empty string.

You could also have solved the problem by reversing the order of your delimiter like this:

String[] temp = myString.split("~~~|~~|~");   

That will first try to split on ~~, before splitting on ~ and will work fine. But you should use the first approach.

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

3 Comments

@Betlista + is a regex quantifier which means match the precedent token 1 or more times. Which means it will also cover ~~~~~~~~~~~ :-)
I know exactly what is the meaning of +, but he is asking to "...contain only the strings separated by ~, ~~ or ~~~.", so maybe "~{1,3}" is better
@Betlista. Hmm. may be you are right. I'll add a not of it in the answer.
4

Just turn the pattern around:

    String myString = "hello world~~hello~~world";
    String[] temp = myString.split("~~~|~~|~");

Comments

3

Try This :

myString.split("~~~|~~|~");

It will definitely works. In your code, what actually happens that when ~ occurs for the first time,it count as a first separator and split the string from that point. So it doesn't get ~~ or ~~~ anywhere in your string though it is there. Like :

[hello world]~[]~[hello]~[]~[world]

Square brackets are split-ed in to 5 different string values.

Comments

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.