Java中的子字符串-长度上限为一个值 [英] Substring in Java - length up to a value

查看:48
本文介绍了Java中的子字符串-长度上限为一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个子字符串,该字符串可以让我最多包含6个字母,但是当我发现一个少于6个字母的姓氏时,这里出现的错误似乎是错误的一个没有成功的解决方案:/

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

它是 .substring(0,6).我需要它最多不超过6个字母(不完全是6个字母).

It's the .substring(0,6). I need it to be up to 6 letters not exactly 6.

错误:

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)

推荐答案

使用

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

这篇关于Java中的子字符串-长度上限为一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆