所以,我试图删除电话号码中的所有特殊字符,只留下数字,不幸的是它不起作用。我已经查找了其他解决方案,但他们仍然没有工作。即使在调试器中运行它之后,似乎.replaceAll()方法根本就没有做任何事情。这是我的代码:
if (c !=null) {
//populate database with first 100 texts of each contact
dbs.open();
//comparator address, count to 100
String addressX = "";
int count = 0;
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
//get c address
String addressY = c.getString(c.getColumnIndex("address"));
addressY.replaceAll("[^0-9]+", "").trim();
//one for the address, other to be able to sort threads by date !Find better solution!
if (!smsAddressList.contains(addressY)) {
//custom object so listview can be sorted by date desc
String date = c.getString(c.getColumnIndex("date"));
smsDateList.add(date);
smsAddressList.add(addressY);
}
//less than 100 texts, add to database, update comparator, add to count
if (count < 100) {
c.moveToPosition(i);
addText(c);
addressX = addressY;
count++;
}
//if more 100 texts, check to see if new address yet
else if (count>100) {
//if still same address, just add count for the hell of it
if (addressX.equals(addressY)) {
count++;
}
//if new address, add text, reset count
else {
addText(c);
addressX = addressY;
count = 1;
}
}
}
}
答案 0 :(得分:4)
String.replaceAll()
返回修改后的字符串,它不会就地修改字符串。所以你需要这样的东西:
addressY = addressY.replaceAll("[^0-9]+", "").trim();
我也很确定trim
在这里是多余的,因为你已经使用replaceAll
剥离空白区域。因此,你可以逃脱:
addressY = addressY.replaceAll("[^0-9]+", "");
答案 1 :(得分:2)
字符串是不可变的。 replaceAll
只返回带有所需修改的新String。
你需要这样做:
addressY = addressY.replaceAll("[^0-9]+", "").trim();
答案 2 :(得分:2)
addressY = addressY.replaceAll("[^0-9]+", "").trim();
replaceAll
方法创建一个新的String,因此您需要分配变量。
答案 3 :(得分:1)
确保将更改后的字符串分配给addressY
addressY = addressY.replaceAll("[^0-9]+", "").trim();