开发者

Split a string all alpha and all numeric

I have a List and I would like to split the first two characters (alpha characters) into a different string and then all the numbers that follow (they vary in length). How could I do tha开发者_如何学运维t?

String wholeString == "AB4578";
String alpha; // this has to be AB
String num; // this has to be 4578

Thank you very much in advance!


Tested and works:

String wholeString = "AB4578";
String alpha = null;
String num = null;

for (int i = 0; i < wholeString.length(); i++) {
    if (wholeString.charAt(i) < 65) {
        alpha = wholeString.substring(0, i);
        num = wholeString.substring(i);
        break;
    }
}

With this approach both the A-z part and the 0-9 part can vary in size, it might not be very effective though considering it's calling charAt(...) for every char in the String.

Hope this helps.


String wholeString = "AB4578";
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);

Must See

  • String.substring(int, int)


If the format is the same, then the answer is already provided. But if the format is not same than you can convert the string into char array and check each character against the ASCII values to check if it is an alphabet or a number.

char[] ch=wholestring.toCharArray();

Now you can apply a for loop for checking each character individually.

for(int l=0; l<ch.length;l++)
{
//code to check the characters
}

And you can separate both types in different strings using StringBuilder or forming two char arrays and then converting them to strings using

String.valueOf(chArray);

ASCII values - http://www.asciitable.com/


Try using the substring method for Strings.

Example:

String alpha = wholeString.substring(0,2);
String num   = wholeString.substring(2);

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring%28int%29


If the format is always the same you can just do this:

String wholeString = "AB4578";
String alpha = wholeString.substring(0, 2);
String num = wholeString.substring(2);


Recommend String API. You would need to use substring operations.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜