具体原理和“查找某个字符或字符段在字符串中出现的次数”一样
/**
* 查找某个字符在字符串中出现的位置信息
*
* @param str 待被查找的字符串
* @param need 待查找的字符
* @return 位置信息的一个二维数组
*/
public static int[][] getStrIndex(String str, String need) {
if (str == null || need == null) {
return null;
}
char strArr[] = str.toCharArray();
int needLen = need.length();
int strLen = str.length();
if (needLen > strLen) {
return null;
}
int count = 0;
boolean flag = true;
List<Integer> start = new ArrayList<Integer>();
for (int i = 0; i < strArr.length; i++) {
StringBuilder builder = new StringBuilder();
for (int j = 0; j < needLen; j++) {
if ((i + j) >= strLen) {
flag=false;
break;
}
builder.append(strArr[i + j]);
}
if (!flag) {
break;
}
if (builder.toString().equals(need)) {
count++;
start.add(i);
}
}
int[][] index = new int[count][2];
for (int i = 0; i < start.size(); i++) {
index[i][0] = start.get(i);
index[i][1] = start.get(i) + (needLen - 1);
}
return index;
}
个人微信公众号: