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?

3
  • 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, 2017 at 4:21
  • appriciate the beauty of simplicity...dont try to make the code complicated when simple solution works well.
    – nits.kk
    Feb 14, 2017 at 4:57
  • @DanLowe—fixed.
    – RobG
    Feb 14, 2017 at 5:01

1 Answer 1

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);
}
3
  • thx a lot for helping
    – Allen Li
    Feb 15, 2017 at 5:08
  • Works like gem.
    – vss
    Jul 27, 2018 at 7:51
  • 3
    23 Apache Commons Lang has a StringUtils.left method for this. String upTo2Characters = StringUtils.left(inputStr, 2); Feb 20, 2019 at 7:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.