如何在Java中为一个字符串句子添加数字?

3

我想使用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.";

}

输入代码


两种方式都可以,例如:String testString = "我今年50岁,而你的年龄在30岁以下。" - RSBS
基本上,给定一个字符串。 - RSBS
正则表达式的帮助 -> java.util.regex.Pattern - Vasily Liaskovsky
如果给定的字符串是固定的,那么可以使用String.charAt()来提取特定位置的数字。但在您发布示例代码之前,我们只能做出假设。 - Themelis
请查看Arvind Kumar Avinash在RSBS的回答。 - Themelis
显示剩余3条评论
6个回答

4

您可以使用printf()格式化您的字符串(链接)

int myAge = 50;
int yourAge = 30;

System.out.printf("My age is %d, and your age is under %d.", myAge, yourAge);

// add five
myAge += 5;
yourAge += 5;

System.out.printf("My age is %d, and your age is under %d.", myAge, yourAge);

输出结果将为:

"My age is 50, and your age is under 30."
"My age is 55, and your age is under 35."

谢谢您的回答,但是我无法定义年龄,因为句子已经给出(“我的年龄是50岁,你的年龄在30岁以下。”),并且应该保存到变量中。我需要提取整数并将数字添加到其中,并将句子保存到变量中。 - RSBS
你看,你应该在问题中提供所有这些细节 :) - Themelis
是的,我刚刚添加了它。感谢您的建议! - RSBS

4

使用正则表达式API,如下:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "My age is 50, and your age is under 30.";

        // The number to be added
        int n = 5;

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            str = str.replace(matcher.group(), String.valueOf(Integer.parseInt(matcher.group()) + n));
        }

        // Display
        System.out.println(str);
    }
}

输出:

My age is 55, and your age is under 35.

1
int myAge = 50;
int yourAge = 30;
String msgStr = "My age is %d, and your age is under %d.";
System.out.printLn(String.format(msgStr, myAge, yourAge));
System.out.printLn(String.format(msgStr, myAge+5, yourAge+5));

抱歉,我添加了更多细节,所以我需要从那里开始。无论如何,感谢您的帮助。 - RSBS

1

age1age2存储为变量,并使用单独的int变量对字符串进行递增,以输出结果。例如:

public int addToString(int increment, int age1, int age2){

String s = "My age is " +(age1 + inc)+ " , and your age is under " +(age2 + inc);

return s; //addToString(5, 50,30) returns: "My age is 55, and your age is under 35"
}

抱歉,我添加了更多细节,句子已经给出,所以我需要从那里开始。无论如何,感谢你的帮助。 - RSBS

1

您有两种方法。如果字符串是由您创建的,则可以使用:

    int age = 50;
    String s = String.format("My age is %d, and your age is under 30.", age);

否则,我建议使用正则表达式来选择数字并重写字符串。例如:
class Scratch {
static Pattern pattern = Pattern.compile("\\d+");

public static void main(String[] args) {
    String string = "My age is 50, and your age is under 30.";
    Matcher matcher = pattern.matcher(string);

    if (matcher.find()) {
        String theAge = matcher.group(0);
    }
  }
}

谢谢您的回答,我确实使用了正则表达式来提取数字。但是我不确定如何将所有数字替换为原始句子。 - RSBS

1
你会得到一个字符串。该字符串可能包含数字。您希望将相同的增量添加到字符串中出现的每个数字上。并且您希望将字符串中出现的每个数字替换为该数字加上增量。
我建议使用Java正则表达式,特别是在Java 9中添加的replaceAll()方法。以下是代码。
import java.util.function.Function;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String str = "My age is 50, and your age is under 30.";
        if (args.length > 0) {
            str = args[0];
        }
        int temp = 5;
        if (args.length > 1) {
            temp = Integer.parseInt(args[1]);
        }
        final int increment = temp;
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);
        Function<MatchResult, String> replacer = new Function<MatchResult, String>() {
            public String apply(MatchResult matchResult) {
                String str = matchResult.group();
                int val = Integer.parseInt(str);
                val += increment;
                return String.valueOf(val);
            }
        };
        String result = matcher.replaceAll(replacer);
        System.out.println(result);
    }
}

请注意,由于java.util.function.Function是一个函数式接口,您可以使用lambda表达式来使代码更短,但我认为上面的代码更易于理解。以下是运行上述代码的结果。
My age is 55, and your age is under 35.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接