Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform the string "AABSSSD" into "2AB3SD"?

Tags:

java

string

I want to transform the string AABSSSD into 2AB3SD (someone called it encryption). This is how I tried to resolve it:

public class TransformString {

    public static void main(String[] args) {
        String str = "AABSSSD";
        StringBuilder newStr = new StringBuilder("");
        char temp = str.charAt(0);
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (temp == str.charAt(i)) {
                count++;
            } else {
                newStr.append(count);
                newStr.append(temp);
                count = 0;
            }
            temp = str.charAt(i);
            if(i == (str.length() - 1)){
                newStr.append(str.charAt(i));
            }
        }
        String x = String.valueOf(newStr);
        x = x.replace("0", "");
        System.out.print(x);
    }
}

But the output is:

2AB2SD

This result is not exactly what I want.

Please help me transform "AABSSSD" into "2AB3SD".

like image 607
Le Phuoc Avatar asked Aug 02 '15 10:08

Le Phuoc


2 Answers

In your else part you should set counter to 1 instead of 0 as new character is having it's first occurrence,

else {
    newStr.append(count);
    newStr.append(temp);
    count = 1;//Just change this
}

and replace 1 instead of 0 from the String x = x.replace("1", ""); because 0A does not look valid as A occurred once in the String so it should be 1A instead of 0A.

like image 128
akash Avatar answered Sep 30 '22 14:09

akash


Your else part is erroneous. Please edit it as:

newStr.append(count);
newStr.append(temp);
count = 1;

instead of:

newStr.append(count);
newStr.append(temp);
count = 0;
like image 20
TryinHard Avatar answered Sep 30 '22 14:09

TryinHard