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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up