开发者

Extracting characters and integer from a string

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

  • V
  • 755
  • D
  • 888
  • B
  • 154

How can i do it ? thanks i开发者_如何学Pythonn advance


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜