Tuesday, May 19, 2009

Index of a sample string in a string

I am sure many of us who write codes in Java use the method indexOf() to get the index of a string in a given string. I use this method quite frequently too and I thought of writing a method that replicates the functionality of indexOf() that is readily available in the Java SDK. In addition to that, I thought this could be an exciting thing to do - dissecting and reverse engineering Java API methods.

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