I have a string
String a="ABC123";
How to increment the above string so that I get the output as :
ABC124
ABC125...and so.
I have a string
String a="ABC123";
How to increment the above string so that I get the output as :
ABC124
ABC125...and so.
 
    
     
    
     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
 }
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?
 
    
     
    
    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
 
    
    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);
