[英]String.replaceAll() not working in my looop
So im trying to remove all the special characters in a phone number to leave just the digits, unfortunately it isn't working. 因此,我试图删除电话号码中的所有特殊字符以仅保留数字,但不幸的是,它不起作用。 I have looked up others solutions but they still arent working.
我查找了其他解决方案,但它们仍然无法正常工作。 Even after running it in a debugger, it seems the .replaceAll() method is simply not doing anything.
即使在调试器中运行它之后,.replaceAll()方法似乎也无济于事。 here is my code below:
这是我的代码如下:
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;
}
}
}
}
String.replaceAll()
returns the modified string, it doesn't modify the string in-place. String.replaceAll()
返回修改后的字符串,它不会就地修改字符串。 So you need something like: 因此,您需要类似:
addressY = addressY.replaceAll("[^0-9]+", "").trim();
I'm also pretty certain that trim
is superfluous here since you're already stripping out white space with the replaceAll
. 我也很确定这里的
trim
是多余的,因为您已经使用replaceAll
去除了空白。 Hence, you can get away with: 因此,您可以摆脱:
addressY = addressY.replaceAll("[^0-9]+", "");
String is immutable. 字符串是不可变的。
replaceAll
simply returns new String with the desired modification. replaceAll
仅返回具有所需修改的新String。
You need to do: 您需要做:
addressY = addressY.replaceAll("[^0-9]+", "").trim();
addressY = addressY.replaceAll("[^0-9]+", "").trim();
replaceAll
方法创建一个新的String,因此您需要重新声明该变量。
确保将更改后的字符串分配给addressY
addressY = addressY.replaceAll("[^0-9]+", "").trim();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.