Whenever there is some operation that you would think is a very common thing to do, yet the Java API requires you to check bounds, catch exceptions, use Math.min()
, etc. (i.e. requires more work than you would expect), check Apache's commons-lang. It's almost always there in a more concise format. In this case, you would use StringUtils#substring
which does the error case handling for you. Here's what it's javadoc says:
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start n characters from the end of the String.
A null String will return null. An empty ("") String will return "".
StringUtils.substring(null, *) = null
StringUtils.substring("", *) = ""
StringUtils.substring("abc", 0) = "abc"
StringUtils.substring("abc", 2) = "c"
StringUtils.substring("abc", 4) = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"