jcotal
jcotal

Reputation: 5

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 that?

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

Thank you very much in advance!

Upvotes: 0

Views: 1551

Answers (6)

Sumit
Sumit

Reputation: 746

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/

Upvotes: 1

whirlwin
whirlwin

Reputation: 16521

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.

Upvotes: 3

chedine
chedine

Reputation: 2374

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

Upvotes: 0

wjans
wjans

Reputation: 10115

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

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240898

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

Must See

Upvotes: 1

sshannin
sshannin

Reputation: 2825

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

Upvotes: 0

Related Questions