Thursday, 11 January 2018

Resolve java.lang.StringIndexOutOfBoundsException while getting substring in Java

Getting substring in Java is very easy. But when we don't  know the size of string or string size is variable, then it becomes difficult.

When I was working a project and I had to get the substring of 10 char long to display on page and this string was coming from database and I didn't know the length of this string and some times this string was less than 10 character.

So it was obvious to get the exception like "java.lang.StringIndexOutOfBoundsException: String index out of range: 10"

Then I started to search the solution for this. After a long search I could not find the simple one line solution to fix this. Every or many solution was based on to first find the null and then get the substring.

But I found the one line solution on stackoverflow by a user linqu.

Solution is given below :-

Suppose I have a string arvind and I want to get a substring of 10 character

class SubStr
{
public static void main(String ar[])
{
String s="arvind";
System.out.println(s.substring(0,10));
}
}

then it will give error like -


So one line solution is -

System.out.println(s.substring(0,Math.min(10, s.length())));





No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...