查找字元串,傳回找的到所有索引
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]