[英]add 1 to all digits in string
我正在处理字符串并解决问题。 问题陈述是“将字符串内的所有数字加一”。我没有得到输入数字 129 和 9923 的所需输出。任何人都可以帮忙!
import java.util.*;
public class Increment {
public static void main(String[] args) {
String number = "129";
int len = number.length();
int i = 0;
int temp = 0;
int before = 0;
int carry = 0;
String result = number;
for (i = len - 1; i >= 0; i--) {
temp = Integer.parseInt(number.charAt(i) + "");
if (temp >= 0 && temp < 9) {
carry = 0;
temp = temp + 1;
result = result.replace(number.charAt(i), (char)(temp + '0'));
} else {
carry = 1;
if (i != 0) {
before = Integer.parseInt(number.charAt(i - 1) + "");
before = before + 1;
result = result.replace(number.charAt(i), '0');
result = result.replace(number.charAt(i - 1), (char)(before + carry));
i = i - 1;
} else {
result = result.replace(number.charAt(i), '0');
result = "1" + result;
}
}
}
System.out.println(result);
}
}
您定义一个添加两个字符串的方法并调用该方法
public static String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1, j = num2.length() - 1;
int carry = 0, sum = 0;
while (i >= 0 || j >= 0) {
sum = carry;
if (i >= 0) sum += num1.charAt(i) - '0';
if (j >= 0) sum += num2.charAt(j) - '0';
sb.append(sum % 10);
carry = sum / 10;
i--;
j--;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
, main
public static void main(String[] args) {
String num1 = "129";
String num2 = "9923";
String res1 = addStrings(num1, "1".repeat(num1.length()));
String res2 = addStrings(num2, "1".repeat(num2.length()));
System.out.println(res1);
System.out.println(res2);
}
,输出
240
11034
我会使用正则表达式,它使它成为一个更简单的解决方案:
public static void main(String[] args) {
String text = "text240 moretext 350 evenmore460text";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String value = matcher.group();
int val = Integer.parseInt(value) + 1;
text = text.replace(value, Integer.toString(val));
}
System.out.println(text);
}
问题是这行代码,查看这里了解更多信息
result = result.replace(number.charAt(i - 1), (char) (before + carry));
您可以像下面这样更改它,但这将替换所有出现的第一个参数,正如@user16320675 指出的那样
result = result.replace(number.charAt(i - 1), Character.forDigit(before + carry, 10));
因此,我建议使用 StringBuilder 而不是 String 以利用 setCharAt(int idx, char c) 方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.