4

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?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Ha Hacker
  • 387
  • 2
  • 6
  • 14

3 Answers3

7

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
6

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'));
George
  • 3,765
  • 21
  • 25
3

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]'));  
Matthew Gunn
  • 4,451
  • 1
  • 12
  • 30