简体   繁体   中英

How to add numbers for a string sentence in Java?

I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like "My age is 55, and your age is under 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() ,

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,

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

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:

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

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. Here is the result of running the above code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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