Issue
The program itself is supposed to take a string and find all the indexes of it inside another string.
Just as an example scanner
stores data from the user, so in this case I've just written it without the use of a scanner
:
String input = "asdesdu";
String largestStr = "sd";
String tempInput = input;
while (tempInput.indexOf(largestStr) != -1) {
int index = tempInput.indexOf(largestStr);
tempInput = tempInput.substring(index + 1);
}
So, from what I can gather the string tempInput
is made with the same value as input
in order for the while loop to stop running after it is run once because the value changes, however my question is why does tempInput
also need to be used to find the index
rather than using the original input
string as shown below:
String tempInput = input;
while (tempInput.indexOf(largestStr) != -1) {
int index = input.indexOf(largestStr);
tempInput = tempInput.substring(index + 1);
}
I'm relatively new to java so any help or feedback is greatly appreciated.
Solution
As I understand the code, it searches for all occurences of largestStr
in input
.
int index = input.indexOf(largestStr);
won't work here because it would always search for the occurence of largestStr
from the beginning of input
. So you will basically always get the same index
.
What would work were saving the last index and searching from that index. Something like:
for (int index = input.indexOf(largestStr); index != -1; index = input.indexOf(largestStr, index + 1)) {
// Do whatever you want with index
}
Answered By - lexicore