For example a phone number will be entered with (-) characters like;
650-212-5710.
A price value may be entered with (,) characters like;
12,500.00
In Java, java.lang.Character class has a method; isDigit() which can be used to identify whether a character is a digit or not. Following method can be used for extracting a numbers-only string.
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
Calling above method with any String will return a numbers-only string.
Thanks for pointing me to the isDigit() method, I hadn't used it before.
ReplyDeleteAdo marune .. wade wenawa thnx!!!
ReplyDeleteThanks for code snippet
ReplyDeleteGracias por el método!
ReplyDeletePura vida!
One could also use regular expressions to form...
ReplyDeletepublic static String getOnlyNumerics(String str) {
return str.replaceAll( "\\D", "" );
}
/Michael H
String result = yourString.replaceAll( "[^\\d]", "" );
ReplyDelete