Reputation: 926
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
Reputation: 53819
If you have Apache Commons Lang, you can simply use substringBefore
:
String[] sf = { StringUtils.substringBefore(s, ",") };
Upvotes: 1
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