簡體   English   中英

在android中的textview中過濾文本

[英]filtering text in a textview in android

有沒有一種方法可以從Android中的TextView中刪除整數。 例如,假設我們有這樣的文本:

123Isuru456Ranasinghe

我希望此文本在刪除整數后像這樣

IsuruRanasinghe

我如何在android中實現呢?

這將為您提供幫助。

  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();
    }

另一個簡單的選擇:

// do it in just one line of code
String num = text.replaceAll(”[\\d]“, “”);

使用刪除數字返回您的字符串。

這只是純Java。 與Android無關。
這是執行所需操作的代碼。

String str = "123Isuru456Ranasinghe";
String newStr = str.replaceAll("[0-9]", "");

經過一些測試,就性能而言,最長的解決方案似乎是最好的!

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);
}

使用循環要快得多。 但是在您的情況下,它有點沒用:p

現在,您必須在“慢速”和“短寫”之間選擇,並且要非常快,但是要復雜一些。 一切都取決於您的需求。

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