Multiply Characters in a String
Write method to make decryption for the
String as the following:
Input: a8b2mBa3d9x7uA
Output:
aaaaaaaabbmmmmmmmmmmmaaadddddddddxxxxxxxuuuuuuuuuu
Let's first see how this problem can be solved using Groovy before we get to Java. We shall create a method that takes in a string as input and returns the desired string.
Our first attempt fails because there is something somehow subtle in the input string -the numbers are given in hexadecimal format, that is base 16.
We definitely have to modify the algorithm. We have to change the way we are converting Strings to integers.
And it works! Next we should move on to the implementation in Java.
And it works! Next we should move on to the implementation in Java.
public class HelloWorld{
public static void main(String []args){
System.out.println(transform("a8b2mBa3d9x7uA") );
}
public static String transform(String str){
String toReturn = "";
String letter = "";
for(int i = 0; i < str.length(); i++){
if(i % 2 == 0){
letter = "" + str.charAt(i);
}else{
int times = Integer.parseInt(""+ str.charAt(i), 16);
String temp = "";
for(int j = 0; j < times; j++){
temp += letter;
}
toReturn = toReturn + temp;
}
}
return toReturn;
}
}
Java > Java2D Code Examples graphic example codes
ReplyDelete