Reputation: 5
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
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
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
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
Reputation: 240898
String wholeString = "AB4578";
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
Must See
Upvotes: 1
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