-4

I'm trying to write for code that searches for the first occurrence of a string (a needle) within another string (a haystack) and return the index of the first character in the matching string.

I've found the following solution online, but I'm having trouble understanding how it works. Can someone please explain to me how it functions?

private static int strStr(String needle, String haystack)
{
    for (int i=0;;i++) {  //
        for (int j=0;;j++) {
            if (j== needle.length()) return i;
            if (i + j == haystack.length()) return -1;
            System.out.println("needle.charAt(j) "+j+" "+needle.charAt(j));
            System.out.println("haystack.charAt(i+j) "+(i+j)+" "+haystack.charAt(i+j));
            if (needle.charAt(j) != haystack.charAt(i + j)) break;
        }
    }
}
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Edward Sun
  • 183
  • 2
  • 12
  • 3
    I expect it's because your question is somewhat vague. *What* don't you understand? Do I need to start with what the `private` keyword does, or do you know that? Do you know how for loops work? Do you know what return statements do? Do you understand the syntax, but don't understand the logic? etc. – azurefrog Jun 24 '16 at 20:25
  • @EdwardSun dont worry, some people have a job of recklessly down voting every question. –  Jun 24 '16 at 20:26
  • 2
    This would be a good read if you're interested in improving your question: [Why is "Can someone help me?" not an actual question?](http://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – azurefrog Jun 24 '16 at 20:26
  • @ritwiksinha: but especially bad questions, ones that haven't shown the fruits of their efforts. – Hovercraft Full Of Eels Jun 24 '16 at 20:27
  • @HovercraftFullOfEels But i think he actually wrote something ,after then he is asking for help, What more effort is needed for this question ? –  Jun 24 '16 at 20:30
  • 1
    @ritwiksinha: the post is little more than "here are my requirements, here is some found code, please explain it". Even you see the shear laziness of this. At least explain what he **does** know in the code, and be much more specific about just what confuses him in the code. You think? – Hovercraft Full Of Eels Jun 24 '16 at 20:32
  • @HovercraftFullOfEels ok, you are correct... sorry... –  Jun 24 '16 at 20:34
  • @ritwiksinha SO is not a tutorial service, it's a searchable database of programming questions and answers. If the OP has a specific, answerable question, they should ask it. "I don't understand, explain it to me" is not such a question. – azurefrog Jun 24 '16 at 20:35
  • @azurefrog ok understandable but i see many reckless down votes here ... –  Jun 24 '16 at 20:36
  • 2
    ... not to mention the friendly message at the top of the code. Perhaps the downvoters scrolled to the right. Sure people will jump up with glee, be happy to help and explain this code from A to Z, after reading that? Or even point at a tutorial? @EdwardSun There are probably more effective ways to ask for help. – Arjan Jun 24 '16 at 20:49

2 Answers2

1
private static int strStr(String needle, String haystack)
{
    for (int i = 0 ; ; i++)
    {
        for (int j = 0 ; ; j++)
        {
            if (j == needle.length())
            {
                return i;
            }

            if (i + j == haystack.length())
            {
                return -1;
            }

            System.out.println("needle.charAt(j) " + j + " " + needle.charAt(j));
            System.out.println("haystack.charAt(i+j) " + (i + j) + " " + haystack.charAt(i+j));

            if (needle.charAt(j) != haystack.charAt(i + j))
            {
                break;
            }
        }
    }
}

First, let's establish a few things:

  • Java starts indices at 0, so needle.charAt(0) is the first character in the string. needle.charAt(3) is the fourth character in the string.
  • The line for(int i = 0 ; ; i++) increments i by one through each iteration, and the for-loop will not cause the loop to stop.

It's easiest to tackle this with an example. Let's use a needle named "hip" and a haystack named "chips". Since Java indices start at 0, we would expect that the method will return 1 (representing the second character), since that's the first character of "hip" within "chips".

  • When we enter the method, we go through the first for-loop. i = 0
  • The next line takes us into another for-loop. i = 0, j = 0
  • j = 0 does not equal needle.length() = 3
  • i + j = 0 + 0 = 0 does not equal haystack.length() = 5
  • needle.charAt(j = 0) is "h", haystack.charAt(i + j = 0 + 0 = 0) is "c". Since "h" is not equal to "c", we break out of the j-for-loop. The break keyword only breaks out of the current loop, so while we stopped executing the j for-loop, we're still within the i-for-loop.
  • We start the next iteration. i = 1
  • The j for-loop restarts at 0. i = 1, j = 0
  • j = 0 does not equal needle.length() = 3
  • i + j = 1 + 0 = 1 does not equal haystack.length() = 5
  • needle.charAt(j = 0) is "h", haystack.charAt(i + j = 1 + 0 = 1) is "h". Since these are equal, we don't break out of the j-for-loop.
  • We start the next iteration of the j for-loop. i = 1, j = 1
  • j = 1 does not equal needle.length() = 3
  • i + j = 1 + 1 = 2 does not equal haystack.length() = 5
  • needle.charAt(j = 1) is "i", haystack.charAt(i + j = 1 + 1 = 2) is "i". Since these are equal, we don't break out of the j-for-loop.
  • We start the next iteration of the j for-loop. i = 1, j = 2
  • j = 2 does not equal needle.length() = 3
  • i + j = 1 + 2 = 3 does not equal haystack.length() = 5
  • needle.charAt(j = 2) is "p", haystack.charAt(i + j = 1 + 2) is "p". Since these are equal, we don't break out of the j-for-loop.
  • We start the next iteration of the j for-loop. i = 1, j = 3
  • j = 3 does equal needle.length() = 3, so we return i = 1.

As we expected, we got 1 back from this function, since "hip" is contained within "chips" starting at position 1 (zero-indexed).

That's all well and good, but what about that i + j == haystack.length() line?

Let's use "ben" as the needle and "bear" as the haystack (we should get back -1, since "ben" does not appear in the word "bear").

         /- needle.length()
         |   /- haystack.length()
         |   |   /- needle.charAt(j)
         |   |   |   /- haystack.charAt(i + j)
         |   |   |   |
 i | j |n.l|h.l|n.c|h.c| result
---+---+---+---+---+---+------------------
 0 | 0 | 3 | 4 | b | b | continue
 0 | 1 | 3 | 4 | e | e | continue
 0 | 2 | 3 | 4 | n | a | break j
 1 | 0 | 3 | 4 | b | e | break j
 2 | 0 | 3 | 4 | b | a | break j
 3 | 0 | 3 | 4 | b | r | break j
 4 | 0 | 3 | 4 |   |   | i + j == haystack.length(), return -1
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
  • Much appreciated the help, its crystal clear now. sorry about the deleted part in my original post, simply ignored those useless comments from folks like Hovercraft Full Of Eels , azurefrog – Edward Sun Jun 25 '16 at 23:52
0

you can use contains() or indexOf() for that. for example:

String str1 = "This is string of words";
String str2 = "string";
int pos = str1.indexOf(str2);

in pos will int with position. Also you can add toUpperCase(), in this case search will be without letter register.

Matt Bearson
  • 228
  • 5
  • 19