2012-04-27 55 views
0

有没有办法在android中从TextView中删除整数。例如,让我们说我们有文字是这样的:在android的文本视图中过滤文本

123Isuru456Ranasinghe

我想这段文字是这样去除整数

IsuruRanasinghe

后如何在android系统实现这一目标?

回答

3

这会帮助你。

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]“, “”); 

与拆卸数字时返回的字符串。

+0

不应该是'if(!Character.isDigit(ch))'? – Rajesh 2012-04-27 08:58:47

+0

@Rajesh:我改变了 – Bhavin 2012-04-27 09:00:06

+0

你也可能想到将方法重命名为'removeDigits'。 – Rajesh 2012-04-27 09:01:25

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

如果你想在处理长字符串期间优化你的应用程序的性能,这个解决方案是非常好的。 – 2012-04-27 09:59:44

3

这仅仅是纯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

现在你必须选择“慢”和短写作,非常快,但有点复杂。全部取决于你需要的东西。