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"
.
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
.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With