String.replaceAll() 在我的循环中不起作用

String.replaceAll() not working in my looop

所以我试图删除 phone 号码中的所有特殊字符以仅保留数字,不幸的是它不起作用。我已经查找了其他解决方案,但它们仍然无法正常工作。即使在调试器中运行它之后,.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;
                    }


                }


            }
        }

字符串是不可变的。 replaceAll 只需 returns 具有所需修改的新字符串。

你需要做的:

addressY = addressY.replaceAll("[^0-9]+", "").trim();
addressY = addressY.replaceAll("[^0-9]+", "").trim();

replaceAll方法创建了一个新的String是否需要给变量赋值

String.replaceAll() returns 修改后的字符串,它不会就地修改字符串。所以你需要这样的东西:

addressY = addressY.replaceAll("[^0-9]+", "").trim();

我也很确定 trim 在这里是多余的,因为你 已经 replaceAll 去掉白色 space .因此,您可以逃脱:

addressY = addressY.replaceAll("[^0-9]+", "");

确保将更改后的字符串分配给 addressY

addressY = addressY.replaceAll("[^0-9]+", "").trim();