Search code examples
javastringreplacedigits

If the String has number inside then square the number and return as a String. How do i replace old number with the squared number Java


So it should work like that

squareDigits("a22b") on "a44b"

squareDigits("a9b2") on "a81b4"

What I have got so far :

public class Code {
    public static void main(String[] args) {
        String ok = "a2b9";
        System.out.println(squareDigits(ok)); // "a81b4"
    }

  public static String squareDigits(String s) {
        char[] pena = s.toCharArray();
        int aboba;
        for (char c : pena) {
            if (Character.isDigit(c)) {
                String s1 = Character.toString(c);
                int b = Integer.parseInt(s1);
                aboba = b * b;
                System.out.println(aboba);
            }
        }
        return "";
        }
    }

Im only beginner and this would very help me out


Solution

  • try as well.

    public static void main(String[] args) {
        String ok = "a2b9";
        System.out.println(squareDigits(ok)); // "a81b4"
    }
    
    public static String squareDigits(String s) {
        StringBuilder sb = new StringBuilder();
        String[] chars = s.split("");
        for (String str : chars){
            if (isNumber(str)){
                int num = Integer.valueOf(str);
                Double square = Math.pow(num, 2);
                sb.append(square.intValue());
            } else {
                sb.append(str);
            }
        }
        return sb.toString();
    }
    
    private static boolean isNumber(String str) {
        try {
            Integer.valueOf(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }