Neek
Neek

Reputation: 19

Extracting characters and integer from a string

I have this String p="V755D888B154" and i want to split it to have this form

How can i do it ? thanks in advance

Upvotes: 0

Views: 421

Answers (3)

MattGrommes
MattGrommes

Reputation: 12354

In your comment you say the letters are fixed, so you if you're just trying to pull out the numbers you could always do something like this. I'll leave it up to you if you think this is a kluge.

String p="V755D888B154";

Integer vPart = Integer.valueOf(p.substring(1,4));
Integer dPart = Integer.valueOf(p.substring(5,8));
Integer bPart = Integer.valueOf(p.substring(9,12));

System.out.println(bPart);

Upvotes: 0

Mateusz Chromiński
Mateusz Chromiński

Reputation: 2832

If your string contains only numbers and strings this snippets workes

    String string = "V755D888B154";
    Pattern p = Pattern.compile("\\d+|\\D+");
    Matcher matcher = p.matcher(string);
    while(matcher.find()) {
        Integer i = null;
        String s = null;
        try {
            i = Integer.parseInt(matcher.group());
        }
        catch (NumberFormatException nfe) {
            s = matcher.group();
        }
        if (i != null) System.out.println("NUMBER: " + i);
        if (s != null) System.out.println("STRING: " + s);
    }

main fail is checking if given String (matcher.group()) consist Integer or not

Upvotes: 0

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

You can use String.split. Example:

String[] numbers = p.split("[a-zA-Z]+");
String[] letters = p.split("[0-9]+");

numbers or letters can have empty string, but you can check it manually.

Upvotes: 1

Related Questions