天天看点

Android 字符串查找,返回所有找到的索引

查找字符串,返回找的到所有索引

private void test() {
        //字符串匹配
        //indexOf
        String a = "你好啊,你好,你还好吗";
        String b = "你";
        String c = "你好";
        Log.e(TAG, "ids: " + getChildIndexFromString(a, b));
    }

    /**
     * 方案一,使用indexOf函数
     * @param parent
     * @param child
     * @return
     */
    private List<Integer> getChildIndexFromString(String parent, String child) {
        int startIndex = 0;
        List<Integer> ids = new ArrayList<>();
        while (parent.indexOf(child, startIndex) != -1) {
            //ids.add(startIndex);
            startIndex = parent.indexOf(child, startIndex);
            Log.e(TAG, "getChildIndexFromString: startIndex=" + startIndex);
            ids.add(startIndex);
            startIndex = startIndex + child.length();
        }
        return ids;
    }
           

结果

2019-11-13 14:48:33.410 10882-10882/? E/MainActivity: getChildIndexFromString: startIndex=0
2019-11-13 14:48:33.410 10882-10882/? E/MainActivity: getChildIndexFromString: startIndex=4
2019-11-13 14:48:33.410 10882-10882/? E/MainActivity: getChildIndexFromString: startIndex=7
2019-11-13 14:48:33.410 10882-10882/? E/MainActivity: ids: [0, 4, 7]
           

继续阅读