getIndexOfSingleChar / getLastIndexOfSingleChar
public static int getIndexOfSingleChar(String str, String singleCharToFind, int targetNum) {
if (str == null || str.length() == 0) {
return -1;
}
if (singleCharToFind == null || singleCharToFind.length() != 1) {
// exception
return -999;
}
int foundNum = 0;
String tmpChar = “”;
int len = str.length();
for (int i=0; i<len; i++) {
tmpChar = str.substring(i, i+1);
if (tmpChar.equals(singleCharToFind)) {
foundNum++;
if (foundNum == targetNum) {
return i;
}
}
}
return -1;
}
public static int getLastIndexOfSingleChar(String str, String singleCharToFind, int targetNum) {
if (str == null || str.length() == 0) {
return -1;
}
if (singleCharToFind == null || singleCharToFind.length() != 1) {
// exception
return -999;
}
int foundNum = 0;
String tmpChar = “”;
int len = str.length();
int lastIdx = len – 1;
for (int i=lastIdx; i>-1; i–) {
tmpChar = str.substring(i, i+1);
if (tmpChar.equals(singleCharToFind)) {
foundNum++;
if (foundNum == targetNum) {
return i;
}
}
}
return -1;
}