Reputation: 11
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
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.
Finite State Automation Based Search
Upvotes: 0
Reputation: 1793
How about this:
I'm sorry but posting code to this elementary problem isn't gonna help you. So I didn't.
Upvotes: 1
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