Search code examples
javastringalgorithmnumberformatexception

How to extract all the integers from a string and convert it to a specified char value in Java?


The problem statement is to find the numbers between a String and find the appropriate character for the given number. To be specific, 0 represents 'a', 1 represents 'b', 2 represents 'c'... like so on. And then again 26 represents 'a', 27- 'b', 28- 'c'....goes on like this.

For better understanding:

Input String: ab1ab

Output: b

Explanation: there is one integer value '1' in the string which represents 'b'.

Input String 2: abcd00hdjhs1224

Output: ac

Explanation: there are two integer values '00' and '1224' which represent 'a' and 'c' respectively.

The problem with my solution was that when I was storing the integer values into int or long data type, large values threw NumberFormatException.

What would be a better approach to overcome this problem? More than a programming problem it's algorithmic problem. How can I achieve the solution without worrying about the large number or the BigInteger class?

Note: If multiple integers occur then the whole is considered as one integer value.(That is where the problem occurs for me)


Solution

  • The modulus operation is distributive over addition and multiplication. i.e.

    • (A+B)%n = (A%n + B%n) %n
    • (A*B)%n = (A%n * B%n) %n

    What is it good for?

    Assume "abcdefgh" represents a large number where a-h are the digits of that number. It is obvious that :

    • abcdefgh = (abcde * 1000 + fgh) or
    • abcdefgh = (a * 10000000 + bcdefgh) or
    • abcdefgh = (a*10000000 + b*1000000 + c*100000 + d*10000 + e*1000 + f*100 + g*10 + h)

    As you are only interested in the reaults of yourDigits%26 you can scan every number found in your input string from left to right and multiply by 10 and add the next number and take the modulo and store this as new answer until you reach the end of the string:

    public static void main(String[] args) { 
        System.out.println(mapNumbersToCharsAndConcat("ab1ab"));
        System.out.println(mapNumbersToCharsAndConcat("abcd00hdjhs1224"));
    }
    static String mapNumbersToCharsAndConcat (String input){
        char[] myChars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        StringBuilder sb = new StringBuilder();       
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(input);
        while(m.find()){
            String num = m.group();
            sb.append(myChars[modFromString(num)]);
        }
        return sb.toString();
    }
    static int modFromString(String num){
        int res = 0;   
        for (int i = 0; i < num.length(); i++){
            res = (res * 10 + (int)num.charAt(i) - '0') % 26; 
        }
        return res; 
    }