【问题标题】:How to increment string variable? [closed]如何增加字符串变量? [关闭]
【发布时间】:2015-07-04 07:07:43
【问题描述】:

我有一个字符串

String a="ABC123";

如何增加上面的字符串以便我得到输出:

ABC124
ABC125...and so.

【问题讨论】:

    标签: java


    【解决方案1】:
     static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+");
    
     static String increment(String s) {
         Matcher m = NUMBER_PATTERN.matcher(s);
         if (!m.find())
             throw new NumberFormatException();
         String num = m.group();
         int inc = Integer.parseInt(num) + 1;
         String incStr = String.format("%0" + num.length() + "d", inc);
         return  m.replaceFirst(incStr);
     }
    
     @Test
     public void testIncrementString() {
         System.out.println(increment("ABC123"));  // -> ABC124
         System.out.println(increment("Z00000"));  // -> Z00001
         System.out.println(increment("AB05YZ"));  // -> AB06YZ
     }
    

    【讨论】:

    • 感谢您的回复。可以让我知道 Pattern.compile("\\d+") 的含义
    • \\d+ 是匹配一个或多个数字的模式(正则表达式)。正则表达式必须编译一次才能匹配。
    【解决方案2】:

    解析为数字并重建为字符串以供将来使用。 解析方面请参考How to convert a String to an int in Java?

    【讨论】:

      【解决方案3】:

      如果字符串必须以这种方式/(您不是生成器)将执行以下操作:

          String a="ABC123";
          String vals[]=a.split("[A-Za-z]+");
      
          int value=Integer.parseInt(vals[1]);
          value++;
          String newStr=a.substring(0,a.length()-vals[1].length())+value;
          System.out.println(newStr);
      

      但是单独生成会更好:

         String a="ABC";
         int val=123;
      
         String result=a+val;
         val++;
         result=a+val;
         System.out.println(""+result);
      

      【讨论】:

        【解决方案4】:

        试试这个

        String letters = str.substring(0, 3); // Get the first 3 letters
        int number = Integer.parseInt(str.substring(3)) // Parse the last 3 characters as a number
        str = letters + (number+1) // Reassign the string and increment the parsed number
        

        【讨论】:

        • 这不适用于所有组合。
        猜你喜欢
        • 1970-01-01
        • 2010-11-20
        • 2012-10-02
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多