有沒有辦法在android中從TextView
中刪除整數。例如,讓我們說我們有文字是這樣的:在android的文本視圖中過濾文本
123Isuru456Ranasinghe
我想這段文字是這樣去除整數
IsuruRanasinghe
後如何在android系統實現這一目標?
有沒有辦法在android中從TextView
中刪除整數。例如,讓我們說我們有文字是這樣的:在android的文本視圖中過濾文本
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]「, 「」);
與拆卸數字時返回的字符串。
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);
}
}
如果你想在處理長字符串期間優化你的應用程序的性能,這個解決方案是非常好的。 – 2012-04-27 09:59:44
這僅僅是純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
現在你必須選擇「慢」和短寫作,非常快,但有點複雜。全部取決於你需要的東西。
不應該是'if(!Character.isDigit(ch))'? – Rajesh 2012-04-27 08:58:47
@Rajesh:我改變了 – Bhavin 2012-04-27 09:00:06
你也可能想到將方法重命名爲'removeDigits'。 – Rajesh 2012-04-27 09:01:25