Jack Pettersson
Jack Pettersson

Reputation: 1666

Conditional substringing in Java

Let's say i have a method for getting the first 3 characters form a string like this:

public static String makeThree(String a){
  return a.toLowerCase().substring(0, 3);
}

Is there any built-in/smart way to handle StringIndexOutOfBoundsException errors, I.E when a String with only 2 characters are given to the method? In which case i want it to just return it as is.

I could build it into an if statement like this:

public static String makeThree(String a){
  if (a.length < 3) {
    return a
  } else {
    return a.toLowerCase().substring(0, 3);
  }
}

but i'm just wondering if there is a better way to go about it.

Upvotes: 1

Views: 1650

Answers (5)

CubeJockey
CubeJockey

Reputation: 2219

Only thing I can suggest is dropping it all down to one line:

return (a.length < 3) ? a : a.substring(0,3).toLowerCase();

This does exactly the same thing as your code:

if (a.length < 3) {
    return a
} else {
    return a.toLowerCase().substring(0, 3);
}

I took a note from the others' answers and moved .toLowerCase() after the substring operation. This prevents unnecessarily changing the cases of letters which would then be dropped.

Upvotes: 6

Pavel Horal
Pavel Horal

Reputation: 18194

Java can be pretty strict and verbose in simple tasks like this. There are multiple projects which are trying to make developers life easier and the code more readable. One of the most popular is Apache Commons and its commons-lang library. I strongly suggest to go through its documentation just to see what it offers and tries to solve.

For your use case there is a nice convenient method StringUtils#left.

Upvotes: 3

Reimeus
Reimeus

Reputation: 159784

If the requirement for not returning a lower-case String less then 3 characters can be relaxed, you could do

public static String getFirst3Chars(String str) {
    return str.toLowerCase().substring(0, Math.min(3, str.length()));
}

Upvotes: 2

Beri
Beri

Reputation: 11620

Only suggestion i would recommend would consist of:

Moving toLowerCase as second operation - in your first if statement you will not upperCase your string when a.length < 3

Like so:

String baseString = (a.length < 3) ? a : a.substring(0,3);
return baseString.toLowerCase();

Upvotes: 1

khelwood
khelwood

Reputation: 59111

There isn't specifically a method for this. You have options like this:

public static String makeThree(String a) {
    return a.substring(0, Math.min(3, a.length())).toLowerCase();
}

This also only converts the substring you actually want to lower case, instead of converting the whole thing and then throwing the rest away.

Upvotes: 1

Related Questions