DEV Community

özkan pakdil
özkan pakdil

Posted on • Originally published at ozkanpakdil.github.io on

Java find how many character repeating in a string

How to find how many characters are repeating in a string.

@Test
void anotherQ() {
    // Q1 -- given a String like aaabbbcccaa need to return output like a3b3c3a2.
    String input = "aaabbbcccazzdddxx";
    char[] arr = input.toCharArray();

    for (int i = 0; i < arr.length; i++) {
        char c = arr[i];
        int charCounter = 1;
        System.out.print(c);
        while (i + 1 < arr.length && c == arr[i + 1]) {
            charCounter++;
            i++;
        }
        System.out.print(charCounter);
    }

    System.out.println("\n" + transformString(input));
}

public static String transformString(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }

    StringBuilder result = new StringBuilder();
    int count = 1;
    char currentChar = input.charAt(0);

    for (int i = 1; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c == currentChar) {
            count++;
        } else {
            result.append(currentChar).append(count);
            count = 1;
            currentChar = c;
        }
    }

    result.append(currentChar).append(count);
    return result.toString();
}

Enter fullscreen mode Exit fullscreen mode

The output is “a3b3c3a1z2d3x2” find the working code here for full working example.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay