Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 298
user1756421 Avatar asked Oct 18 '12 13:10

user1756421


People also ask

How do you use substring length?

The substring begins with the character at the specified index and extends to the end of this string. substring(int beginIndex, int endIndex) : The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex).

How do you limit the length of a string in Java?

Java 9 provides a codePoints() method to convert a String into a stream of code point values. Here, we used the limit() method to limit the Stream to the given length. Then we used the StringBuilder to build our truncated string.

What does length () do in Java?

Java String length() Method The length() method returns the length of a specified string.

Is length () a string in Java?

The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. The length() method can also be used for StringBuilder and StringBuffer classes.


2 Answers

I prefer

secondName.length > 6 ? secondName.substring(0, 6) : secondName
like image 140
João Mendes Avatar answered Oct 26 '22 06:10

João Mendes


Use

secondName.substring (0, Math.min(6, secondName.length()))
like image 34
Denys Séguret Avatar answered Oct 26 '22 06:10

Denys Séguret