I have to String objects:
String first = \"/Some object that has a loop in it object/\";
String second = \"object\";
What I need to do is find
The simplest way is to use indexOf
in a loop, advancing the starting index each time that you find the word:
int ind = 0;
int cnt = 0;
while (true) {
int pos = first.indexOf(second, ind);
if (pos < 0) break;
cnt++;
ind = pos + 1; // Advance by second.length() to avoid self repetitions
}
System.out.println(cnt);
This will find the word multiple times if a word contains self-repetitions. See the comment above to avoid such "duplicate" finds.
Demo on ideone.