问题
I'm trying to make a substring which lets me have up to 6 letters of a surname, however what I have here seems to throw an error when it finds a surname of less than 6 letters, I have been looking for hours for a solution with no sucess :/
id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,6).toLowerCase();
System.out.print ("Here is your ID number: " + id);
It's the .substring(0,6)
. I need it to be up to 6 letters not exactly 6.
The error:
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)
回答1:
Use
secondName.substring (0, Math.min(6, secondName.length()))
回答2:
I prefer
secondName.length > 6 ? secondName.substring(0, 6) : secondName
回答3:
Try the Apache Commons StringUtils class.
// This operation is null safe.
org.apache.commons.lang.StringUtils.substring(secondName, 0, 6);
回答4:
This can be a solution: Check length of 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);
回答5:
Though you didn't provide the error, it was pretty easy to spot 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 might 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);
回答6:
You'll be getting a java.lang.StringIndexOutOfBoundsException.
You need to make sure the length is always less than the string length. Something like
int len = Math.min(6, secondName.length());
String id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,len).toLowerCase();
来源:https://stackoverflow.com/questions/12955890/substring-in-java-length-up-to-a-value