MATLAB: Count occurrences of sub-string in a long string (How many times a sub-string appear)

countMATLABstrings

I have a very long string which contains lots of MAC address, see below: str_long = '3A9059D46237,2047DAACE894,2047DAACE894,2047DAACE894,2047DAACE894,…'
Each sub-string is a MAC address, e.g. 3A9059D46237. They are separated by a comma.
How can I count the occurrences of each sub-string?
Should I use a loop to do this? Your suggestion and ideas are highly appreciated. Thanks in advance

Best Answer

>> str = '3A9059D46237,2047DAACE894,2047DAACE894,2047DAACE894,2047DAACE894';
>> C = regexp(str,'\w+','match');
>> [uni,~,idx] = unique(C);
>> cnt = histc(idx,unique(idx));
>> uni{:}
ans = 2047DAACE894
ans = 3A9059D46237
>> cnt(:)
ans =
4
1
If you want that displayed nicely you could use fprintf:
>> uni(2,:) = num2cell(cnt);
>> fprintf('%s:%4d\n',uni{:})
2047DAACE894: 4
3A9059D46237: 1