Well, I wrote this code and would like to share with the readers of this blog. I hope you find it useful. Please feel free to drop a line if you have a better way to solve this problem. The code is quite self explanatory. It mainly reads through the original string and while reading it, the sample string is being compared.
// To get the index of the first occurrence of a matching substring
public static int indexOf(String inputString, String sampleString){
// set the length of input string
int length = inputString.length();
int inputStringIndex = -1;
StringBuffer newString = new StringBuffer();
// to keep track of current index of character of input string
int index = 0;
// to keep track of current index of character of sample string
int check = 0;
while (index < length) {
try {
if (inputString.charAt(index) == sampleString.charAt(check)) {
newString.append(inputString.charAt(index));
check++;
if (newString.toString().equals(sampleString)) {
/**
* set the index of the first occurrence of the
* matching substring
*/
inputStringIndex = (index - check) + 1 ;
break;
}
}
} catch (Exception ex){}
index++;
}
return inputStringIndex;
}
0 comments:
Post a Comment