2

I have a string

String a="ABC123";

How to increment the above string so that I get the output as :

ABC124
ABC125...and so.
Madhan
  • 5,750
  • 4
  • 28
  • 61
TodayILearned
  • 1,440
  • 4
  • 20
  • 28

4 Answers4

5
 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
 }
  • Thanks for reply. Could let me know meaning of Pattern.compile("\\d+") – TodayILearned Jul 04 '15 at 13:15
  • 1
    `\\d+` is an pattern (regular expression) that matches one or more digits. The regular expression must be compiled once before matching. –  Jul 04 '15 at 15:03
0

Parse as number and rebuild as a string for future usage. For parsing aspects please refer How to convert a String to an int in Java?

Community
  • 1
  • 1
Robert Navado
  • 1,319
  • 11
  • 14
0

Try this

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
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
0

If the String has to be in this way/(you are not the generator) would have done something like:

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

But it will be better if you generate it seperately:

   String a="ABC";
   int val=123;

   String result=a+val;
   val++;
   result=a+val;
   System.out.println(""+result);
joey rohan
  • 3,505
  • 5
  • 33
  • 70