我需要对字符串中的数字执行算术运算。我知道我需要将这些数字解析出来,转换为 int,进行数学运算,然后再转换回 String。
例子:
n = 2。
输入数据:“建筑物高 350 英尺,周长 400 英尺”。
输出数据:建筑物高 352 英尺,周长 402 英尺”。
我让我的 for 循环遍历字符串,我可以影响数字的值,但我很难把它放回一个新的、修改过的字符串中。
这是我现在所在的位置,但它不起作用
String output = new String(); String tempString = new String(); int newNumb = 0; int n = 2; for (int i = 0; i < output.length(); i++){ Pattern integerPattern = Pattern.compile('-?\\d+'); Matcher matcher = integerPattern.matcher(output); newNumb = (Integer.parse(output) + n); tempString = output.replace(output, String.valueOf(newNumb));