I have a string inside a cell, for example '5a5ac66'
. I want to count the number of digits and chars in that string.
'5a5ac66'
= 4 digits (5566) and 3 chars (aac)
How can I do that? Is there any function in MATLAB?
Yes, there's a built-in function for that, isstrprop
. It tells you which characters are within the given range, in your case 'digit'
or 'alpha'
. You can then use nnz
to obtain the number of such characters:
str = {'5a5ac66'};
n_digits = nnz(isstrprop(str{1},'digit')); %// digits
n_alpha = nnz(isstrprop(str{1},'alpha')); %// alphabetic
If you have a cell array with several strings:
str = {'5a5ac66', '33er5'};
n_digits = cellfun(@nnz, isstrprop(str,'digit')); %// digits
n_alpha = cellfun(@nnz, isstrprop(str,'alpha')); %// alphabetic
A simple (not necessarily optimal) solution is the following:
digits = sum(x >= '0' & x <= '9');
chars = sum((x >= 'A' & x <= 'Z') | (x >= 'a' & x <= 'z'));
You could do it with regular expressions. For example:
s = '5a5ac66';
digit_indices = regexp(s, '\d'); %find all starting indices for a digit
num_digits = length(digit_indices); %number of digits is number of indices
num_chars = length(regexp(s, '[a-zA-Z]'));