我有一个字符串
String a="ABC123";
如何增加上面的字符串以便我得到输出:
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
}
关于java - 如何增加字符串变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31217970/