Ren
Ren

Reputation: 4680

Split()-ing in java

So let's say I have:

String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");

String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];

Is there any easier way of making this code work? My objective is to get all the numbers separated, whether stringArray includes nonImportantData or not. Should I maybe use the substring method?

Upvotes: 1

Views: 239

Answers (3)

erickson
erickson

Reputation: 269857

I'd probably remove the unimportant data before splitting the string.

int idx = string1.indexOf('*');
if (idx >= 0)
  string1 = string1.substring(0, idx);
String[] arr = string1.split(", ");

If '*' is always present, you can shorten it like this:

String[] arr = str.substring(0, str.indexOf('*')).split(", ");

This is different than MarianP's approach because the "unimportant data" isn't preserved as an element of the array. This may or may not be helpful, depending on your application.

Upvotes: 1

Dave
Dave

Reputation: 6189

Assuming you always have the format you've provided....

String input = "123,234,345,456,567*nonImportantData";
String[] numbers = input.split("\\*")[0].split(",");

Upvotes: 1

MarianP
MarianP

Reputation: 2759

Actually, the String.split(...) method's argument is not a separator string but a regular expression.

You can use

String[] splitStr = string1.split(",|\\*");

where | is a regexp OR and \\ is used to escape * as it is a special operator in regexp. Your split("*") would actually throw a java.util.regex.PatternSyntaxException.

Upvotes: 2

Related Questions