This is the third solution to extract characters and numbers from an alpha numeric value into separate strings. This program uses the simple predicate and predicates chaining to check for characters and numbers.
import java.util.Scanner;
import java.util.function.Predicate;
public class Alphanumeric {
public static void main(String[] args) {
Scanner inpAlphaNumeric = new Scanner (System.in);
StringBuilder strNumbers=new StringBuilder();
StringBuilder strLetters=new StringBuilder();
//Defining three Predicates
Predicate<Character> lowercaseChar = (ch) -> ch >='a' && ch <='z';
Predicate<Character> uppercaseChar = (ch) -> ch >='A' && ch <='Z';
Predicate<Character> numberChar = (ch) -> ch >='0' && ch <='9';
System.out.println("Enter an alpha numeric string (Ex:- H93Wkq61f)");
String inpStr=inpAlphaNumeric.next();
int strLen=inpStr.length();
//Comparing within the range of ASCII's of Alphabets and Numbers
while (--strLen >= 0) {
if (uppercaseChar.or(lowercaseChar).test(inpStr.charAt(strLen)))
strLetters.append(inpStr.charAt(strLen));
else
if (numberChar.test(inpStr.charAt(strLen)))
strNumbers.append(inpStr.charAt(strLen));
}
inpAlphaNumeric.close();
System.out.println("The string of characters extracted from "+inpStr+" is="+strLetters.reverse().toString());
System.out.println("The string of numbers extracted from "+inpStr+" is="+ Integer.valueOf(strNumbers.reverse().toString()));
System.out.println("Add 1 to the Extracted number "+Integer.valueOf(strNumbers.toString())+" + "+"1="+(Integer.valueOf(strNumbers.toString())+1));
}
}
OUTPUT:
Enter an alpha numeric string (Ex:- 381BY4kjLpq6)
tl920Kjq4Gb
The string of characters extracted from tl920Kjq4Gb is=tlKjqGb
The string of numbers extracted from tl920Kjq4Gb is=9204
Add 1 to the Extracted number 9204 + 1=9205

Leave a comment