Java substring - length to value

I am trying to create a substring that allows me to have up to 6 letters of a last name, however, what seems to cause an error here when she finds a last name less than 6 letters, I was looking for a clock for a solution without sucess: /

id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,6).toLowerCase(); System.out.print ("Here is your ID number: " + id); 

This is .substring(0,6) . I need it to consist of 6 letters of at least 6.

Mistake:

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6 at java.lang.String.substring(Unknown Source) at Test.main(Test.java:27) 
+7
source share
6 answers

Using

 secondName.substring (0, Math.min(6, secondName.length())) 
+31
source

I prefer

 secondName.length > 6 ? secondName.substring(0, 6) : secondName 
+2
source

It may be a solution: Check the length of the surname and decide accordingly

 if (secondName.length() >6) id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,6).toLowerCase(); else id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,secondName.length()).toLowerCase(); System.out.print ("Here is your ID number: " + id); 
+1
source

Try the Apache Commons StringUtils class.

 // This operation is null safe. org.apache.commons.lang.StringUtils(secondName, 0, 6); 
+1
source

Although you did not report this error, it was fairly easy to identify the problem:

  id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,6<secondName.length()?6:secondName.length).toLowerCase(); System.out.print ("Here is your ID number: " + id); 

EDIT . This may be more readable:

  id = firstName.substring (0,1).toLowerCase() + (6<secondName.length()?secondName.substring(0,6):secondName).toLowerCase(); System.out.print ("Here is your ID number: " + id); 
0
source

You will get java.lang.StringIndexOutOfBoundsException.

You need to make sure that the length is always less than the length of the string. Something like

 int len = Math.min(6, secondName.length()); String id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,len).toLowerCase(); 
0
source

All Articles