user3376818
user3376818

Reputation: 61

How to split the string with slash

How do I split the string using forward slash? I've tried with following code:

I have string String x="10/20//30;expecting values 10,20,30.

When I tried to split using x.split("/"); then it only splitting 10,20,"",30
When I tried to split using x.split("//"); then it only splitting 10/20,30.

Please help me to split correctly. Is there any way to skip the one slash if there are 2 slashes present?

Regards, murali

Upvotes: 1

Views: 7486

Answers (4)

Reimeus
Reimeus

Reputation: 159754

You could do

String[] array = x.split("/+");

Upvotes: 7

FatalMerlin
FatalMerlin

Reputation: 1540

Because I can't comment on previous answer:

I think it has to be like

String[] s = x.split("/+");

Because otherwise it would be a conversion from String Array to String, wouldn't it?

Upvotes: 1

brso05
brso05

Reputation: 13222

It's splitting fine when you use x.split("/") the problem is it is inserting a blank where the // slash is because of how the split works it will return an array of [10, 20, , 30]. Just either remove all blanks from the array or when you process just skip elements that are blank.

Upvotes: 0

Karol Tyl
Karol Tyl

Reputation: 348

Try to use your first approach and remove empty value from the result, in example by using the solution described here: Remove Null Value from String array in java

Upvotes: 0

Related Questions