开发者

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 b开发者_StackOverflow社区umped as to how to do it.

Any help would be appreciated

Thanks


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.


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 ?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜