javaregex

String Expansion program gives incorrect output


Input - 'a2b3c1' Expected Output - 'aabbbc'

Actual Output - 'aaabbbbcc'

I am not sure why is it printing the input alpha char again. What could I possibly change here to get the right output

The following is my program:

public class stringExpansionAndCompression {

    public void getStringInput() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the String value: ");
        String inputStr = reader.readLine();
        String output = stringExpansionRegEx(inputStr);
        System.out.println(output);
    }

    public String stringExpansionRegEx(String str) {

        StringBuilder result = new StringBuilder();

        Pattern pattern = Pattern.compile("([a-zA-Z]\\d)+");
        Matcher match = pattern.matcher(str);

        boolean bool = Pattern.matches("([a-zA-Z]\\d)+", str);
        if (bool = true){
            for (int i=0;i<str.length();i++)  {
                     char ch = str.charAt(i);
                     int count = Integer.parseInt(String.valueOf(str.charAt(i+1)));
                     for (int j = 0; j <= count; j++) {
                         result.append(ch);
                     }
                     i=i+1;
            }
        }
        return result.toString();
    }

}

Solution

  • Since the index of the for loop in this case starts from 0 and the step size is 1, in order for the number of loops to meet the requirement (count), you need to control the loop boundary to "< = count - 1" or "< count", otherwise the number of loops will be "count + 1"

    Modify the second level for loop to

         for (int j = 0; j < count; j++) {
            result.append(ch);
         }