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

标签 java android string replaceall

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


                }


            }
        }

最佳答案

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

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

我也很确定 trim 在这里是多余的,因为您已经replaceAll 去除了空白。因此,您可以逃脱:

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

关于java - String.replaceAll() 在我的循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791116/

相关文章:

android - PagerSlidingTabStrip 使 horizo​​ntalscrollview 的宽度固定

PHP:非常简单的编码/解码字符串

php - 简单的字符串替换字符

android - Genymotion 设备没有出现在设备选择器上 - Android Studio

java - 如何用Java读取MySQL数据库

java - 当 JVM 达到一定的堆大小时,如何停止 Camel 路由?

Java Map get 方法返回 null

android - 如何在服务中设置 START_STICKY

java - 仅替换字符串中第二次出现的位置

java - Binary Search 仅当搜索项为偶数时才创建无限循环