Let the input and search strings be
in_str = 'ABAAAFDAFDBBFGGBHHSFAFDAFDAFDBB' search_str = 'AFD'
We can use strfind to get the starting indexes for the search string in the input string and from those that find consecutive search string groups -
idx = strfind(in_str,search_str) grp_matches = diff(idx)==numel(search_str)
So, now we have the βislandsβ of zeros and ones, where the islands of them represent the presence of consecutive grouped search bites. Then we must find the length of the islands, and the maximum length of the island - the desired result -
df1 = diff([0 grp_matches 0]) %// Perform differentiation of matches
The end of the islands will be designated β-1β as a result of differentiation, and β1β will mean the beginning of these islands. Thus, (find(df1==-1) - find(df1==1))+1 will be the length of the island. The end result will be max this -
out = max(find(df1==-1) - find(df1==1))+1
Summing up the discussion , all the code could be turned into a compact version, for example:
df1 = diff([0 diff(strfind(in_str,search_str))==numel(search_str) 0]) out = max(find(df1==-1) - find(df1==1))+1
source share