我想在字符串中自动增加整数(是产品代码) 例如:ABC00001 - > ABC00002; ABC00009 - > ABC00010 ....和ABC99999 - > ABC000001 ... 它只是增加整数。我不知道如何解决它,因为它有数字" 0000"。 我搜索一个函数:
public static void main(String[] args) {
Pattern digitPattern = Pattern.compile("(\\d)"); // EDIT: Increment each digit.
Matcher matcher = digitPattern.matcher("test001check2");
StringBuffer result = new StringBuffer();
while (matcher.find())
{
matcher.appendReplacement(result, String.valueOf(Integer.parseInt(matcher.group(1)) + 1));
}
matcher.appendTail(result);
System.out.println(result.toString());
}
但它会使每个数字都折皱。我该如何解决?
答案 0 :(得分:0)
如果我理解你的问题,一种可能的方法是从String
获取前3个字符,然后将其他所有字符提取到int
。然后,您可以使用类似
private static String increment(String str) {
String base = str.substring(0, 3);
int val = Integer.parseInt(str.substring(4));
return String.format("%s%06d", base, val + 1);
}
然后测试它
public static void main(String[] args) {
String str = "ABC000001";
System.out.println(str);
System.out.println(increment(str));
}
输出
ABC000001
ABC000002
答案 1 :(得分:0)
public static void main(String[] args) {
// use \d+ to match the whole number
Pattern digitPattern = Pattern.compile("(\\d+)");
Matcher matcher = digitPattern.matcher("test001check2");
StringBuffer result = new StringBuffer();
while (matcher.find())
{
String match = matcher.group(1);
int numDigits = match.length(); // get number of digits in the string
int newValue = Integer.parseInt(matcher.group(1)) + 1; // get the raw value of the string, add one
// pad the new value with the right number of zeros, so 001 will become 002 and not just 2
String newValueStr = String.format("%0" + numDigits + "d", newValue);
matcher.appendReplacement(result, newValueStr);
}
matcher.appendTail(result);
System.out.println(result.toString());
}
我机器上的输出:test002check3
答案 2 :(得分:0)
好的,抱歉我的问题不清楚。我只想增加mix字符串中的最后一个整数。 例如:test001check2 - > test001check3; test001check9-> test001check00; test001check09 - > test001check10; test001check99 - > test001check000 .... 现在我发现了一个具有上述要求的功能。
public final char MIN_DIGIT = '0';
public final char MAX_DIGIT = '9';
public String incrementedCode(String original) {
if(original != null && !"".equals(original.trim())){
StringBuilder buf = new StringBuilder(original);
int i = buf.length() -1;
while(i >= 0) {
char c = buf.charAt(i);
if(c >= MIN_DIGIT && c<= MAX_DIGIT){
c++;
if(c > MAX_DIGIT) { // overflow, carry one
if(buf.charAt(i - 1) > MAX_DIGIT){
buf.setCharAt(i, MIN_DIGIT);
buf.insert(i, "0");
return buf.toString();
}
buf.setCharAt(i, MIN_DIGIT);
i--;
continue;
}
buf.setCharAt(i, c);
return buf.toString();
}
i--;
}
// overflow at the first "digit", need to add one more digit
buf.insert(0, MIN_DIGIT);
return buf.toString();
}else{
return "";
}
}