3

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.

3
  • So you want a String array where the first element is the substring of s from 0 to the index of the first occurrence of , right? Why not String sd[] = {s.split(",")} Commented Nov 5, 2015 at 14:32
  • Because only the first element is desired. Yes it is easy to get the first element from that but the OP wants it in one line :) Commented Nov 5, 2015 at 14:37
  • Just append the second line to the first line without a newline inbetween and you've got your one-liner! Commented Nov 5, 2015 at 14:38

3 Answers 3

9

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 ','.

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

Comments

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

Comments

1

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

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

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.