Matlab R2015中字符串中的数字和字符计数函数

Matlab R2015中字符串中的数字和字符计数函数,matlab,function,char,counting,digits,Matlab,Function,Char,Counting,Digits,我在单元格中有一个字符串,例如'5a5ac66'。我想数一数那个字符串中的位数和字符数 '5a5ac66'=4位数字(5566)和3个字符(aac) 我该怎么做?MATLAB中有任何函数吗?一个简单(不一定是最优)的解决方案如下: digits = sum(x >= '0' & x <= '9'); chars = sum((x >= 'A' & x <= 'Z') | (x >= 'a' & x <= 'z')); digits=s

我在单元格中有一个字符串,例如
'5a5ac66'
。我想数一数那个字符串中的位数和字符数

'5a5ac66'
=4位数字(5566)和3个字符(aac)

我该怎么做?MATLAB中有任何函数吗?

一个简单(不一定是最优)的解决方案如下:

digits = sum(x >= '0' & x <= '9');
chars = sum((x >= 'A' & x <= 'Z') | (x >= 'a' & x <= 'z'));

digits=sum(x>='0'&x='A'&x='A'&x您可以使用正则表达式来实现。例如:

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

是的,有一个内置函数。它告诉您哪些字符在给定范围内,在您的情况下是
'digit'
'alpha'
。然后您可以使用获取这些字符的数量:

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

谢谢。它很有效。你的答案的计算负担较小。其他答案的计算成本可能较低。这是一个很好的解决方案。它也适用于非西方字符。@AlexFeinman谢谢你的评论!我不知道
isstrprop
能做到这一点(尽管它完全有意义)