public class SmartCounter {
public String SmartCounter(String strID){
intNumber =Integer.parseInt(strID.replaceAll("\\D+",""));
intNumber += 1;
strReturn = "ABCD"+intNumber+"XYZL";
(strReturn);
}
}
我只是问我如何在Number部分中添加1并将其返回到字符串中而不会丢失零? TIA:D
答案 0 :(得分:1)
假设id
的格式为
您可以使用Regex解析它,增加数字,然后重建它。像这样:
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(\\D{4})(\\d{9})(\\D{4})");
final String input = "ABCD000000001XYZL";
final Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
final String head = matcher.group(1);
final long number = Long.parseLong(matcher.group(2)) + 1;
final String tail = matcher.group(3);
final String result = String.format("%s%09d%s", head, number, tail);
System.out.println(result);
}
}
你可以使用snazzier Regex和Matcher.appendReplacement
来缩短代码;以复杂性为代价:
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(?<=\\D{4})(\\d{9})(?=\\D{4})");
final String input = "ABCD000000001XYZL";
final Matcher matcher = pattern.matcher(input);
final StringBuffer result = new StringBuffer();
if (matcher.find()) {
final long number = Long.parseLong(matcher.group(1)) + 1;
matcher.appendReplacement(result, String.format("%09d", number));
}
matcher.appendTail(result);
System.out.println(result);
}
答案 1 :(得分:0)
看看DecimalFormat我相信你可以自己弄明白
答案 2 :(得分:0)
你可以使用String.format(String, Object...)
之类的东西,
class SmartCounter {
private int id = 1;
public SmartCounter() {
this.id = 1;
}
public SmartCounter(int id) {
this.id = id;
}
public String smartCounter() {
return String.format("ABCD%09dXYZL", id++);
}
}
您可以像
一样运行public static void main(String[] args) {
SmartCounter sc = new SmartCounter();
for (int i = 0; i < 3; i++) {
System.out.println(sc.smartCounter());
}
}
输出
ABCD000000001XYZL
ABCD000000002XYZL
ABCD000000003XYZL