Count the number of characters and insert a new one in a certain position, in a string?

0

I have both strings:

String num_tel1 = "03184872882" and String num_tel2 = "84872882" . They are 11 and 8 characters respectively. How do I count this number of characters and, if you have a String with 11 characters (num_tel1), insert the number 9, just after the 031 and, if you have 8 characters, enter the number 9 in the first position, ie before of the first 8 (num_tel2)?

    
asked by anonymous 28.06.2017 / 01:34

2 answers

4

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.
    
28.06.2017 / 01:51
1

I have a function that I always use, which is to validate the phone. I'm going to put what you need here to work so I'll try to give you a light. In case it's all static because it's a Util class I have. I modified it for your blz case:

public static final String TELEFONE_REGEX = "([0-9]{4}[0-9]{3}[1-9]9?(\d{2})?).*";

public static String getTelefone(String telefone, Context context) {
        Pattern phoneRegex = Pattern.compile(TELEFONE_REGEX);

        telefone = reverseStr(telefone.replaceAll("\D", ""));

        Matcher m = phoneRegex.matcher(telefone);

        if (m.matches())
            telefone = m.group(1);

        telefone = reverseStr(telefone);

        if (telefone.length() == 8)
            telefone = "9" + telefone;
        if (telefone.length() == 11)
            telefone = telefone.substring(0,3) + "9" + telefone.substring(3, telefone.length()-1);

        return telefone;
    }

public static String reverseStr(String input) {
        String output = "";
        for (int i = input.length() - 1; i >= 0; i--) output += input.charAt(i);
        return output;
    }

This function validates if the input is a phone itself, and checks in reverse.

    
28.06.2017 / 16:10