i have a string splitted into different positions in a list e.g.,
List<String> str = new ArrayList<String>();
str.add("This is a ");
str.add("[{searched");
str.add("_placeholder}]");
str.add(" in this string.");
I want to search "[{searched_string}]" in a list and want to know which is the starting and the ending position of "[{searched_string}]" in the list. E.g., in the above list the starting position of the "[{searched_string}]" is 1 and 2 respectively.
Can someone please guide me with any algorithm that can return me the starting and the ending position of the string being searched?
Would something like the below code work? It is not very efficient, but seems to work. For the list in the question, with the searched string as searched_placeholder
, it returns a start index of 1 and end index of 2.
List<String> str = new ArrayList<String>();
str.add("This is a ");
str.add("[{searched");
str.add("_placeholder}]");
str.add(" in this string.");
String searchString = "searched_placeholder";
StringBuilder completeString = new StringBuilder();
int endIndex = 0;
int startIndex = 0;
for (int index = 0; index < str.size(); index++) {
completeString.append(str.get(index));
if (completeString.indexOf(searchString) != -1) {
endIndex = index;
break;
}
}
for (int index = 0; index <= endIndex; index++) {
completeString.replace(0, str.get(index).length(), "");
if (completeString.indexOf(searchString) == -1) {
startIndex = index;
break;
}
}
System.out.println("Start index: " + startIndex + ", End index: " + endIndex);