MATLAB: Find char consecutive in a string

charconsecutive charstring

Hi! I have this string
stringa={stringa1; stringa2; stringa3; stringa4};
stringa1='{a(abc)(ac)d(cf)}';
stringa2='{(ad)c(bc)(ae)}';
stringa3='{(ef)(ab)(df)cb}';
stringa4='{eg(af)cbc}';
and I want to find per every string (stringa1, stringa2 ..) the number of 'ab' 'ba'. a and b not must be consecutive. I try strfind but it's not give me the right answer. Can you help me? Thanks

Best Answer

Thanks for clarifying. You still haven't my answered my question about whether or not a character can be part of several matches or if the matches can intersect (see my 'a***a***b***b' example).
Assuming the answer is no to both questions, the simplest way is to use a regular expression:
stringa1='{a(abc)(ac)d(cf)}';
stringa2='{(ad)c(bc)(ae)}';
stringa3='{(ef)(ab)(df)cb}';
stringa4='{eg(af)cbc}';
stringa={stringa1; stringa2; stringa3; stringa4};
matchstarts = regexp(stringa, 'a.+?b'); %for 'ab'
matchcounts = cellfun(@numel, matchstarts)
The regular expression above says match 'a', followed by as little as necessary (the ?) but at least one (the +) characters, followed by a 'b'.
For 'ba', the regular expression would then be 'b.+?a'
Note that if the answer is yes to either question, regular expressions won't work.