You can use the StringBuilder: : Insert to insert the number 9 in the position you want according to the size of your String
.
We can do this:
public static void main(String[] args) {
System.out.println(formatString("03184872882"));
System.out.println(formatString("84872882"));
}
public static String formatString(String s) {
StringBuilder sBuilder = new StringBuilder(s);
sBuilder.insert(s.length() == 11 ? 3 : 0, "9");
return sBuilder.toString();
}
Output :
031984872882
984872882
See that I used a ternary operator to insert the number 9 in the correct position according to the size of the string. Basically, the ternary operator does this:
if(s.length() == 11) sBuilder.insert(3, "9"); // Insere o número 9 na quarta posição da 'String', depois do DDD.
else sBuilder.insert(0, "9"); // Insere o número na primeira posição da string.