-2

How to find a sequence of digits and multiply only those sequence of digits with number 2 in JAVA?

Let's say I have a string "My age is 19". How do I get a string "My age is 38" as the output?

Also, how do I reverse that multiplied number in the string later on. For above example input, the second output should be "My age is 83"

I tried using java.util.regex.Pattern. It works. However, is there any other way we can do that. Probably through converting the string into an array? I tried. But I am struck at multiplying sequence of characters in the string. Instead I am able to multiple each digit. But I want the sequence of digits to be multiplied by 2. For instance, in above example, I am able to multiply each digit 1 and 9 by 2. But I want 19 as a 2 digit number to be multiplied by 2.

smech
  • 1
  • 1
  • 2
    Please show us what you have done already ... so that we can understand what part of the problem is giving you difficulty. – Stephen C Sep 06 '20 at 06:09
  • Use the [String#replaceAll()](https://www.tutorialspoint.com/java/java_string_replaceall.htm) method: `String yourString = "My age is 20"; String num = yourString.replaceAll("[^\\d+]", ""); if (num.matches("\\d+")) { yourString = yourString.replaceAll(num, String.valueOf(Integer.parseInt(num) * 2)); } System.out.println(yourString);` – DevilsHnd - 退職した Sep 06 '20 at 17:39

3 Answers3

1

I'm assuming you are saying multiplying the whole string "My age is 20" by 2. If so, there is no way to achieve your desired output.

What you can do is, loop over the whole string, find a section which appear to be in numeric form and check for that section. There are several ways to check if a string is digit and some of them are discussed in the following link.

How to check if a String is numeric in Java

After that, you can perform multiplication on a (parsed) digit-string then add them back to the string.

Hung Vu
  • 443
  • 3
  • 15
1

You can use regular expression and do something like this

    //set regexp pattern with group representing number
    Pattern pattern = Pattern.compile("My age is (\\d+)");
    //get number from string
    Matcher matcher = new Matcher(pattern, "My age is 20");
    matcher.find();
    int age = Integer.parseInt(matcher.group(1));
    //multiply
    int result = age * 2;
Artur Vakhrameev
  • 794
  • 7
  • 11
1

Try this.

Pattern pat = Pattern.compile("\\d+");
String s = "My age is 19";
String doubled = pat.matcher(s).replaceAll(m -> "" + Integer.valueOf(m.group()) * 2);
System.out.println(doubled);
String reversed = pat.matcher(doubled).replaceAll(m -> new StringBuilder(m.group()).reverse().toString());
System.out.println(reversed);

output

My age is 38
My age is 83