简体   繁体   English

如何为Java中的字符串句子添加数字?

[英]How to add numbers for a string sentence in Java?

I want to add numbers using Java.我想使用 Java 添加数字。

For example, the sentence is given String: "My age is 50, and your age is under 30."例如,给句子字符串:“我的年龄是 50 岁,而你的年龄是 30 岁以下。” If I want to add 5 to the sentence, it should be like "My age is 55, and your age is under 35."如果我要在句子中加 5,应该是“我的年龄是 55,而你的年龄在 35 岁以下”。

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.限制是给定句子,所以你需要从句子中提取数字并将数字添加到原始句子中。

I was trying to split by space (" ") and try to add numbers after that.我试图按空格(“”)分割,然后尝试添加数字。 But I don't know how to substitute numbers with the original sentence.但我不知道如何用原句替换数字。

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.我很困惑,因为当我试图用“”分割时它有逗号,即使你可以从句子中提取所有数字,我也不知道如何才能将数字恢复为字符串。

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.";

}

} enter code here } 在此处输入代码

You can format your string using printf() ,您可以使用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);

The output will be, output 将是,

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

Use regex API as follows:使用正则表达式 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);
    }
}

Output: Output:

My age is 55, and your age is under 35.
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));

Store age1 and age2 as variables and use a separate int for increment string to output the result. age1age2存储为变量,并使用单独的 int 将字符串递增到 output 结果。 For example:例如:

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"
}

You have 2 ways.你有两种方法。 If the string is created by you you can use:如果字符串是由您创建的,您可以使用:

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

Otherwise I suggest something like a regex to pick the numbers and rewrite the string.否则,我建议使用正则表达式来选择数字并重写字符串。 For instance:例如:

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);
    }
  }
}

You are given a string.给你一个字符串。 The string may contain numbers.字符串可能包含数字。 You want to add the same increment to each number that appears in the string.您想为字符串中出现的每个数字添加相同的增量。 And you want to replace each number appearing in the string with that same number plus the increment.并且您想用相同的数字加上增量替换字符串中出现的每个数字。

I suggest using java regular expressions, in particular method replaceAll() which was added in Java 9. Here is the code.我建议使用 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);
    }
}

Note that since java.util.function.Function is a functional interface, you can use a lambda expression which may make the code shorter but I think the code above is easier to understand. Note that since java.util.function.Function is a functional interface, you can use a lambda expression which may make the code shorter but I think the code above is easier to understand. Here is the result of running the above code.这是运行上述代码的结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM