我想使用Java来进行数字相加。
比如,给定一个字符串:"My age is 50, and your age is under 30." 如果我想要在这个句子中加上5,那么结果应该是"My age is 55, and your age is under 35."
限制条件是给定了句子,因此您需要从句子中提取数字并将数字添加到原始句子中。
我尝试通过空格(" ")进行拆分,并尝试在其后添加数字。但我不知道如何用原始句子替换其中的数字。
我感到困惑,因为在尝试通过" "进行拆分时有逗号,即使您可以从句子中提取出所有数字,我也不确定如何将数字还原回字符串。
public class Main {
public static Pattern pattern = Pattern.compile("\\d+");
public static String addNumber(String str, int n) {
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String theAge = matcher.group(0);
int newAge = Integer.parseInt(theAge) + n;
}
String addSentence = str;
return addSentence;
}
public static void main(String[] args) {
String testString = "My age is 50, and your age is under 30.";
String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";
String newSent = addNumber(testString, 5);
// -> should be "My age is 55, and your age is under 35.
String newSent2 = addNumber(testString2, 10);
// -> should be "My age is 60, and your age is under 40 and my friend age is 54.";
}
输入代码
java.util.regex.Pattern
- Vasily LiaskovskyString.charAt()
来提取特定位置的数字。但在您发布示例代码之前,我们只能做出假设。 - Themelis