Andulos
Andulos

Reputation: 475

A simple decryption in Java

I am writing a method to decrypt a input string. The encryption is straight forward. Any repeating character in the string is replaced by the character followed by the number of times it appears in the string. So, hello is encrypted as hel2o. Below is the decryption logic I have so far. It works but is so imperative and involves multiple loops. How can this be improved?

String input = "hel2o";
    String[] inarr = input.split("\\s+");
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < inarr.length; i++) {
        String s = inarr[i];
        char[] c = s.toCharArray();
        for(int j = 0; j < c.length; j++) {
            if(Character.isDigit(c[j])) {
                for(int x = 0; x < Character.getNumericValue(c[j])-1; x++) {
                    sb.append(c[j-1]);
                }
            } else {
                sb.append(c[j]);
            }
        }
    }

System.out.printl(sb.toString());

Upvotes: 0

Views: 4391

Answers (1)

Igor Flakiewicz
Igor Flakiewicz

Reputation: 793

You pretty much asked for a solution but I had fun doing it so I'll share.

You can do it with one loop, by doing some clever appending. Also, unlike yours, my solution will work with multi digit numbers e.g. Hel23o will convert to helllllllllllllllllllllllo with 23 l's.

String input = "hel23o";

StringBuilder builder = new StringBuilder();
char previousChar = ' ';
StringBuilder number = new StringBuilder();
for (char c : input.toCharArray()) {
    if (Character.isDigit(c)) {
        number.append(c);
        continue;
    }

    if (number.length() > 0 ) {
        int count = Integer.parseInt(number.toString());
        count = count > 1 ? count - 1 : 0;
        builder.append(String.join("", Collections.nCopies(count, String.valueOf(previousChar))));
    }

    builder.append(c);
    previousChar = c;
    number.setLength(0);
}

Alternatively without the multi digit number support:

String input = "hel3o";

StringBuilder builder = new StringBuilder();
char previousChar = ' ';
for (char c : input.toCharArray()) {
    if (Character.isDigit(c)) {
        builder.append(String.join("", Collections.nCopies(Character.getNumericValue(c) - 1, String.valueOf(previousChar))));
        continue;
    }

    builder.append(c);
    previousChar = c;
}

Upvotes: 1

Related Questions