user753334
user753334

Reputation: 11

Finding index of a substring in Java

I have a question.

Suppose we have two strings str1, str2. The strings can be anything. Now, we need to create a method which searches str1 for str2 and returns the index no. of the first occurrence of str2 in str1, and returns -1 if not found. But we cannot use string.indexOf method.

I am bumped as to how to do it.

Any help would be appreciated

Thanks

Upvotes: 1

Views: 724

Answers (3)

gshauger
gshauger

Reputation: 745

If you want to really impress your professor do the following...

Find a library that will perform a Powerset Construction OR write your own code that will essentially generate a DFA from your search string. Then iterate over your string and the DFA one character at a time and if you end up at a accept state you've found it.

As you iterate over your string keep track of the index of the current character. If your DFA accepts then simply subtract the search string length from the current index and you have you starting index in the string.

Powerset Construction

Finite State Automation Based Search

Upvotes: 0

Nam Nguyen
Nam Nguyen

Reputation: 1793

How about this:

  1. for each position in str1 that is less than or equal to str1.length() - str2.length()
    1. grab str1's substring whose length is str2.length() from that position
    2. compare this substring with str2, if match, return the position
  2. return -1

I'm sorry but posting code to this elementary problem isn't gonna help you. So I didn't.

Upvotes: 1

Vincent B.
Vincent B.

Reputation: 514

Just use the method myString.GetChartAt(index); to do what you wanna do. (e.g. use it in a system of loops to compare the strings str1 and str2). Another way could be to consider regex to achieve what you want, this sounds like homework, what are the others constraints ?

Upvotes: 0

Related Questions