Check and change the first 3 characters of a string?

Asked

Viewed 42 times

0

For example, a string with phone +5531984892883. I would like to check if the first 3 characters are +55. If they are +55, replace them with 0 (zero). How can I do that?

  • The problem with that is that if the country code is exactly 5 and soon after you see the number started with 5, your program goes to bag. heuhe;

1 answer

3


Use the method replace:

final String telefone = "+5531984892883";
final String outroTelefone = "31984892883";

System.out.println("Telefone :" + telefone);
System.out.println("Telefone sem o codigo :" + telefone.replace("+55", "0"));
System.out.println();

System.out.println("Outro telefone :" + outroTelefone);
System.out.println("Outro telefone sem o codigo :" + outroTelefone.replace("+55", "0"));

Exit:

Telefone :+5531984892883
Telefone sem o codigo :031984892883

Outro telefone :31984892883
Outro telefone sem o codigo :31984892883

Online example here.

  • It is necessary to check before, to replace. As there may not be these characters, there is some problem in not checking?

  • @Henriquemendes is not required. See updated response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.