【问题标题】:Substring in Java - length up to a valueJava中的子字符串 - 长度不超过一个值
【发布时间】:2012-10-08 23:37:27
【问题描述】:

我正在尝试创建一个子字符串,它可以让我拥有最多 6 个姓氏的字母,但是当我找到少于 6 个字母的姓氏时,我在这里似乎会抛出一个错误,我一直在寻找几个小时对于没有成功的解决方案:/

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 个。

错误:

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)

【问题讨论】:

    标签: java string substring


    【解决方案1】:

    使用

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

    【讨论】:

    • Math.min(6, secondName.length())6 如果secondName.length()>6,则在其他情况下是secondName.length()
    • secondName.lenght() 获取字符串的长度。 Math.min() 获取最小值,这意味着如果字符串的长度小于 6,则返回该值。但是如果字符串的长度大于 6,则返回 6。
    • @RolfSmit - 问题是我需要它达到 6
    【解决方案2】:

    Try the Apache Commons StringUtils class.

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

    【讨论】:

    • 感谢修复@ihebiheb
    【解决方案3】:

    我更喜欢

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

    【讨论】:

      【解决方案4】:

      这可以是一个解决方案: 检查姓氏的长度并据此决定

      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】:

        虽然您没有提供错误,但很容易发现问题:

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

        编辑这可能更具可读性:

         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】:

          您将收到 java.lang.StringIndexOutOfBoundsException。

          您需要确保长度始终小于字符串长度。类似的东西

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-06-11
            • 2012-09-08
            • 1970-01-01
            • 2013-09-27
            • 1970-01-01
            • 2012-09-24
            相关资源
            最近更新 更多