Separate String Number Letters

Asked

Viewed 3,293 times

7

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

Ex.:

Entree:

"A1B2C3D2Z9"

Exit:

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

Use a for to traverse the string, only that I don’t know how to identify in the condition that checks whether the position of the string is a number or a letter.

Does anyone know how I can take this conditional test?

4 answers

16


Check if the character is a number, using Character.isDigit().

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

Below the validating code, letters, numbers and other character types.

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 on Github for future reference.

  • Character does not store Unicode symbols not? Only letters and numbers same?

  • I mean the other symbols, like ®.

  • 1

    Good, @diegofm. I added the reply. Thank you.

5

  • I question the same case of the other answer, not every character is only letter or number, the second validation can bring wrong results.

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();

3

It’s just the solution of 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 on the list.

  • 1

    I liked the solution! +1 Only your description got a little "aggressive" =D

  • Sorry. I wanted to be ironic. I started using, and I’m still adapting.

Browser other questions tagged

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