Finding needle in haystack

I am writing a program that is supposed to loop through two strings to find an occurrence of a word inside of a larger word and return the index at which the two strings begin to match. for example, heat in theatre would return 2 because that is the position where the strings begin to match. However, when I compile my code, i always return 0, and i can't figure out why. Can someone help? Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int find(string needle, string haystack) {
  int i, j;
  for (i=0; i<haystack.size(); i++) {    // i is my index for caterpillar
    for (j=0; j<needle.size(); j++) {    // j is my index for pill
      if (i+j < haystack.size ()) {
      if (haystack[i+j] != needle[j]) {
          break;
      }
      }
    }
    return i;
  }
  return -1;
}

int main(){
  cout << find("pill", "caterpillar") << endl;
}
If we simplify your code to the pertinent section...
1
2
3
4
5
6
  for (i=0; i<haystack.size(); i++) {    // i is my index for caterpillar
    for (j=0; j<needle.size(); j++) {    // j is my index for pill
        // do stuff
    }
    return i;
  }


... this might make it more clear that no matter what is happening in that inner for loop, you will always reach the "return i" line on the first iteration of your outer for loop, no matter what, where i == 0.

As far as I can see, your code needs a bit more work because you need to first determine the first index where it finds "p", and then once you have a possible match, you need to keep iterating through the length of "pill" to make sure all 4 letters match as well.
Last edited on
Hmm I notice that now. Also, wouldn't I need some type of argument to tell the for loop to continue looping if i+j < haystack.size() ?

1
2
3
4
5
6
7
8
int find(string needle, string haystack) {
   int i, j;
   for (i=0; i<haystack.size(); i++) {    // i is my index for caterpillar
     for (j=0; j<needle.size(); j++) {    // j is my index for pill
       if (i+j < haystack.size ()) {
           // something here to tell the loop to keep looping?
       if (haystack[i+j] != needle[j]) {
          break;
Topic archived. No new replies allowed.