Eric G
Eric G

Reputation: 926

Java - Better way to split a string into just one array

I only want the first element from s.split(",") and I need to return value to be in a String array.

How can I make this code a one liner?

String [] sd = s.split(",");
String [] sf = new String[]{sd[0]};

I tried s.split(",",1); but it just adds it all to the first element without actually splitting it.

Upvotes: 3

Views: 803

Answers (3)

Jean Logeart
Jean Logeart

Reputation: 53819

If you have Apache Commons Lang, you can simply use substringBefore:

String[] sf = { StringUtils.substringBefore(s, ",") };

Upvotes: 1

Mark Sholund
Mark Sholund

Reputation: 1312

String [] sf = new String[]{s.split(",")[0]};

Upvotes: 9

Eran
Eran

Reputation: 393821

You can use

String [] sf = {sd.substring(0,sd.indexOf(','))};

If you only need the first token of the comma separated String, using substring and indexOf would be more efficient than split.

Of course this code will throw an exception if the input String doesn't contain a ','.

Upvotes: 9

Related Questions