22

I got a java question which is Given a string, return the string made of its first two chars, so the String "Hello" yields "He".

If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".

Note that str.length() returns the length of a string.

public String firstTwo(String str) {          

 if(str.length()<2){
     return str;
 }
 else{
     return str.substring(0,2);
 }
}

I'm wondering is there any other way can solve this question?

KishanCS
  • 1,357
  • 1
  • 19
  • 38
Allen Li
  • 479
  • 1
  • 5
  • 11
  • What's the problem with your existing code? I guess if you felt the need you could make it a oneliner `return str.length() > 2 ? str.substring(0,2) : str;` but I don't feel that this really adds anything. – CollinD Feb 14 '17 at 04:21
  • appriciate the beauty of simplicity...dont try to make the code complicated when simple solution works well. – nits.kk Feb 14 '17 at 04:57
  • @DanLowe—fixed. – RobG Feb 14 '17 at 05:01

1 Answers1

47

Your code looks great! If you wanted to make it shorter you could use the ternary operator:

public String firstTwo(String str) {
    return str.length() < 2 ? str : str.substring(0, 2);
}
Andrew Jenkins
  • 1,590
  • 13
  • 16