parsing/converting task with characters and numbers within

  • A+
Category:Languages

It is necessary to repeat the character, as many times as the number behind it.

They are positive integer numbers.

case #1  input: "abc3leson11"  output: "abccclesonnnnnnnnnnn" 

I already finish it in the following way:

    String a = "abbc2kd3ijkl40ggg2H5uu";     String s = a + "*";     String numS = "";     int cnt = 0;     for (int i = 0; i < s.length(); i++) {         char ch = s.charAt(i);         if (Character.isDigit(ch)) {             numS = numS + ch;             cnt++;         } else {             cnt++;             try {                 for (int j = 0; j < Integer.parseInt(numS); j++) {                     System.out.print(s.charAt(i - cnt));                 }                 if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {                     System.out.print(s.charAt(i));                  }             } catch (Exception e) {                 if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {                     System.out.print(s.charAt(i));                  }             }             cnt = 0;             numS = "";         }      } 

But I wonder is there some better solution with less and cleaner code?

 


Using java basic string regx should make it more terse as follows:

public class He1 {     private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(//d+).*");       // match the number between or the last using regx;     public static void main(String... args) {         String s = "abc3leson11";         System.out.println(parse(s));         s = "abbc2kd3ijkl40ggg2H5uu";         System.out.println(parse(s));     }      private static String parse(String s) {         Matcher matcher = pattern.matcher(s);         while (matcher.find()) {             int num = Integer.valueOf(matcher.group(1));             char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);              // locate the char before the number;             String repeated = new String(new char[num-1]).replace('/0', prev);              // since the prev is not deleted, we have to decrement the repeating number by 1;             s = s.replaceFirst(String.valueOf(num), repeated);             matcher = pattern.matcher(s);         }         return s;     } } 

And the output should be:

abccclesonnnnnnnnnnn abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: