I'm trying to write a code that returns an Array whose elements are the indices of the word(occurences) that I'm looking for in a string : ex) d Input:
String sent = "Hi is Hi is Hi is";
String find = "Hi";
ArrayList<Integer> index = indexFinder(sent,find);
For(int i=0;i<index.size(),i++)
System.out.println(index.get(i));
Output:
0
6
12
It would be very nice if Java had a string slicing function like python.. but since it does not.. I tried to use substring() method.
import java.util.ArrayList;
public class recursionEx {
ArrayList<Integer> index = new ArrayList<Integer>();
ArrayList<Integer> indexFinder(String sent, String find){
int pos =0;
int subPos =0;
if(sent.contains(find)==false){
return index;
}
else if(sent.contains(find)){
pos = sent.indexOf(find);
index.add(pos);
subPos = pos+find.length();
return indexFinder(sent.substring(subPos),find);
}
return index;
}
public static void main(String[] args) {
String sent = "Hi is Hi is Hi is";
String find = "Hi";
recursionEx r = new recursionEx();
ArrayList<Integer> g = r.indexFinder(sent, find);
for(int i=0;i<g.size();i++){
System.out.println(g.get(i));
}
}
}
the output was
0
4
4
In hindsight, I'm gettng the substring of the original String sent every iteration, thus elements in index Array are the indices of the String find in substring of String sent which are 0,4,4.
How can I fix this to get the desired output? Any help is appreciated!
You should not use the substring as parameter, but only the start of the search in the string. Here is a way that works, it is not perfect, try to make it better :
import java.util.ArrayList;
public class recursionEx {
ArrayList<Integer> index = new ArrayList<Integer>();
String string;
recursionEx(String string){this.string = string;}
ArrayList<Integer> indexFinder(int position, String find){
int pos =0;
int subPos =0;
if(string.substring(position).contains(find)==false){
return index;
}
else if(string.substring(position).contains(find)){
pos = string.substring(position).indexOf(find) + position;
index.add(pos);
subPos = pos+find.length();
return indexFinder(subPos,find);
}
return index;
}
public static void main(String[] args) {
String sent = "Hi is Hi is Hi is";
String find = "Hi";
recursionEx r = new recursionEx(sent);
ArrayList<Integer> g = r.indexFinder(0, find);
for (Integer pos : g)
System.out.println(pos);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments