简体   繁体   English

在android中的textview中过滤文本

[英]filtering text in a textview in android

Is there a way to remove integers from TextView in android. 有没有一种方法可以从Android中的TextView中删除整数。 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? 我如何在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. 这只是纯Java。 Nothing to do with Android. 与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 但是在您的情况下,它有点没用: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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM