user1756421
user1756421

Reputation: 213

Substring in Java - length up to a value

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)

Upvotes: 15

Views: 11827

Answers (6)

Rob Breidecker
Rob Breidecker

Reputation: 604

Try the Apache Commons StringUtils class.

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

Upvotes: 5

pallavi
pallavi

Reputation: 139

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); 

Upvotes: 1

pillingworth
pillingworth

Reputation: 3238

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();

Upvotes: 0

João Mendes
João Mendes

Reputation: 1425

I prefer

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

Upvotes: 6

ppeterka
ppeterka

Reputation: 20726

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); 

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

Use

secondName.substring (0, Math.min(6, secondName.length()))

Upvotes: 42

Related Questions