Sunday, May 24, 2009

Indexes of indexOf

Have you ever come across a situation in which you want to gather a list of indexes of the one particular substring in a string but you are limited to using only indexOf() method? I did and I wrote this method to ease my work in the future in the event that I need to get the list of indexes of the given substring. The code is as follow.

public static ArrayList indices(String inputString, String sampleString){
int length = inputString.length();
int inputStringIndex = -1;
StringBuffer newString = new StringBuffer();
int index = 0;
int check = 0;
ArrayList compile = new ArrayList();
while (index < length) {
try {
if (inputString.charAt(index) == sampleString.charAt(check)) {
newString.append(inputString.charAt(index));
check++;
if (newString.toString().equals(sampleString)) {
inputStringIndex = (index - check) + 1 ;
compile.add(inputStringIndex);
newString.setLength(0);
}
}
if (check == (sampleString.length())) {
check = 0;
}
} catch (Exception ex){}
index++;
}
if (compile.size() == 0) {
compile.add(inputStringIndex);
}
return compile;
}
The usage of this static method is very simple and trivial. Given a string "Nicholas Key Key Key Nicholas Key" and a sample substring "Key", you will get the result of [9, 13, 17, 30].

1 comment:

  1. Looks somewhat clumsy for a trivial method. I'd question the use case for it. Why would I need the starting point of each occurrence? I can think of two scenarios - when you want to replace the sampleString or count the number of samples. If it's the case why wouldn't you use regular expressions?

    ReplyDelete