Java provides a method to check whether a character is a digit. For this you can use Character.isDigit(char).
public static String squareNumbers(String input) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i); // get char at index
if (Character.isDigit(c)) // check if the char is a digit between 0-9
output.append((int) Math.pow(Character.digit(c, 10), 2)); // square the numerical value
else
output.append(c); // keep if not a digit
}
return output.toString();
}
This will iterate any passed string character by character and square each digit it finds. If for example 2 digits are right next to each other they will be seen as individual numbers and squared each and not as one number with multiple digits.
squareNumbers("10")
-> "10"
squareNumbers("12")
-> "14"
squareNumbers("abc2e4")
-> "abc4e16"