Function for counting digits and char in a string in Matlab R2015

I have a row inside a cell, for example '5a5ac66'. I want to count the number of digits and characters in this line.

'5a5ac66'= 4 digits (5566) and 3 characters (aac)

How can i do this? Is there any function in MATLAB?

+4
source share
3 answers

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'));
+6
source

Yes, there is a built-in function for this isstrprop. It tells you which characters are in a given range, in your case 'digit'or 'alpha'. Then you can use nnzto get the number of such characters:

str = {'5a5ac66'};
n_digits = nnz(isstrprop(str{1},'digit')); %// digits
n_alpha = nnz(isstrprop(str{1},'alpha')); %// alphabetic

:

str = {'5a5ac66', '33er5'};
n_digits = cellfun(@nnz, isstrprop(str,'digit')); %// digits
n_alpha = cellfun(@nnz, isstrprop(str,'alpha')); %// alphabetic
+7

. :

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]'));  
+3

Source: https://habr.com/ru/post/1615011/


All Articles