You can use the method Stringbuilder::Insert to insert the number 9 in the position you want according to the size of your String
.
We can do it this way:
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
Note 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.
thanks! Just an addendum to the reply, the ternary operator, within the Internet, from stringbuilder, at least in the case of android studio, did not work. But that’s what I wanted.
– Henrique
Hmm... I had tested here and it worked normally, how strange! But I’m glad I helped somehow. Thanks! :))
– itscorey
I also found it strange, but switching to normal operators worked normally. Anyway, thank you again!
– Henrique