Separate letters from String numbers

7

I need to separate the characters of a string into numbers and letters.

Ex:

Entry:

  

"A1B2C3D2Z9"

Output:

List<Character> numeros = { '1','2', '3' }
List<Character> letras = { 'A', 'B', 'C' }

I use a for to go through string , but I do not know how to identify in the condition that it checks whether the position of the string is a number or a letter.

Does anyone know how I can do this conditional test?

    
asked by anonymous 09.02.2017 / 17:04

4 answers

16

Make sure the character is a number, using Character.isDigit() .

You should note that other symbols can be used. So it would be good to use the Character.isLetter() to validate if the character is actually a letter. (Thanks to the @ diegofm for noticing this).

Below the validating code, letters, numbers and other types of characters.

String input = "A1B2C3D2Z9®*#"; //adicionei uns símbolos pro exemplo fazer sentido

List<Character> letras = new ArrayList<>();
List<Character> numeros = new ArrayList<>();
List<Character> outros = new ArrayList<>();

for (char c : input.toCharArray()) {
    if (Character.isDigit(c)) {
        numeros.add(c);
    } else if (Character.isLetter(c)) {
        letras.add(c);
    } else {
        outros.add(c);
    } 
}

I put the code in GitHub for future reference

    
09.02.2017 / 17:10
5

In the Character library you have a isDigit method that checks whether the character is a number from 0-9

char c = string.charAt(0);
if (Character.isDigit(c)) {
    //É numero
} else {
    //É letra
}

In this Gringo OS question you have several ideas: link

    
09.02.2017 / 17:10
4

Simple alternative using replaceAll and regex

String input = "A1B2C3D2Z9";
String letters = input.replaceAll("[^a-zA-Z]+", "");
String numbers = input.replaceAll("[^0-9]+", "");

//Para transformar em array
letters.toCharArray();
numbers.toCharArray();
    
09.02.2017 / 18:22
3

It's just the solution to the same problem with another flavor.

String chars = "A1B2C3D44F555";
List <Character> letters = chars.chars().
                              boxed().
                              map(ch -> (char) ch.intValue()).
                              filter(Character::isLetter).
                              collect(Collectors.toList());
List <Character> digits = chars.chars().
                             boxed().
                             map(ch -> (char) ch.intValue()).
                             filter(Character::isDigit).
                             collect(Collectors.toList());

This solution is slower by doing Autoboxing twice in the list.

    
09.02.2017 / 18:13