java - How do I reverse the order of only the digits in a string? -


given string in java, how can obtain new string adjacent sequences of digits reversed?

my code:

import static java.lang.system.*;  public class p2 {     public static void main(string[] args)     {         if(args.length < 1)         {             err.printf("usage: java -ea p2 string [...]\n");             exit(1);         }          string[] norm = new string[args.length];         for(int = 0; i<norm.length;i++)         {             norm[i] = args[i];         }     }      public string invertdigits(string[] norm)     {         } } 

and example, should do:

inputs: 1234 abc9876cba a123 312asd a12b34c56d

1234 -> 4321

abc9876cba -> abc6789cba

a123 -> a321

312asd -> 213asd

a12b34c56d -> a21b43c65d

although question heavily downvoted, proposed problem seems clear now. chose solve using regular expression match in recursive function.

private static string reversedigits(string s) {     // pattern match sequence of 1 or more digits     matcher matcher = pattern.compile("\\d+").matcher(s);     // fetch position of next sequence of digits     if (!matcher.find()) {         return s; // no more digits     }     // keep before number     string pre = s.substring(0, matcher.start());     // take number , reverse     string number = matcher.group();     number = new stringbuilder(number).reverse().tostring();      // continue rest of string, concat!     return pre + number + reversedigits(s.substring(matcher.end())); } 

and here's iterative approach.

private static string reversedigits(string s) {     //if (s.isempty()) return s;     string res = "";     int base = 0;     matcher matcher = pattern.compile("\\d+").matcher(s);     while (!matcher.hitend()) {         if (!matcher.find()) {             return res + s.substring(base);         }         string pre = s.substring(base, matcher.start());         base = matcher.end();         string number = matcher.group();         number = new stringbuilder(number).reverse().tostring();         res += pre + number;     }     return res; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -