简体   繁体   中英

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

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. (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM