Is there a way to remove integers from TextView
in android. For example let's say we have text like this:
123Isuru456Ranasinghe
I want this text to be like this after removing integers
IsuruRanasinghe
How do I achieve this in android?
This will Help you.
public static String removeDigits(String text) {
int length = text.length();
StringBuffer buffer = new StringBuffer(length);
for(int i = 0; i < length; i++) {
char ch = text.charAt(i);
if (!Character.isDigit(ch)) {
buffer.append(ch);
}
}
return buffer.toString();
}
Another Simple Option :
// do it in just one line of code
String num = text.replaceAll(”[\\d]“, “”);
Return your string with Removing Digits.
This is just pure java. Nothing to do with Android.
Here is the code to do what you want.
String str = "123Isuru456Ranasinghe";
String newStr = str.replaceAll("[0-9]", "");
After some tests, it seems that the longest solution is the best in the matter of performance !
public static void main(String[] arg) throws IOException {
// Building a long string...
StringBuilder str = new StringBuilder();
for (int i = 0; i < 1000000; i++)
str.append("123Isuru456Ranasinghe");
removeNum1(str.toString());
removeNum2(str.toString());
}
// With a replaceAll => 1743 ms
private static void removeNum1(String _str) {
long start = System.currentTimeMillis();
String finalString = _str.replaceAll("[0-9]", "");
System.out.println(System.currentTimeMillis() - start);
}
// With StringBuilder and loop => 348 ms
private static void removeNum2(String _str) {
long start = System.currentTimeMillis();
StringBuilder finalString = new StringBuilder();
char currentChar;
for (int i = 0; i < _str.length(); ++i) {
currentChar = _str.charAt(i);
if (Character.isLetter(currentChar)) {
finalString.append(currentChar);
}
}
System.out.println(System.currentTimeMillis() - start);
}
Using a loop is much faster. But in your case, it is a bit useless :p
Now you have to choose between "slow" and short to write and very fast but a bit more complicated. All depend of what you need.
StringBuilder ans = new StringBuilder();
char currentChar;
for (int i = 0; i < str.length(); ++i) {
currentChar = str.charAt(i);
if (Character.isLetter(currentChar)) {
ans.append(currentChar);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.