Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract first two characters of a String in Java [closed]

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?

like image 303
Allen Li Avatar asked Feb 14 '17 04:02

Allen Li


People also ask

How do you find the first two characters of a string?

Use the String. slice() method to get the first two characters of a string, e.g. const first2 = str. slice(0, 2); . The slice method will return a new string containing the first two characters of the original string.

How do you extract the first 5 characters from the string str?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How do you extract the first 5 characters from the string Java?

To access the first n characters of a string in Java, we can use the built-in substring() method by passing 0, n as an arguments to it. 0 is the first character index (that is start position), n is the number of characters we need to get from a string.


1 Answers

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);
}
like image 197
Andrew Jenkins Avatar answered Sep 28 '22 01:09

Andrew Jenkins