在 Matlab R2015 中计算字符串中数字和字符的函数
function for counting digits and char in string in Matlab R2015
我在单元格中有一个字符串,例如 '5a5ac66'
。我想计算该字符串中的数字和字符数。
'5a5ac66'
= 4 位数字 (5566) 和 3 个字符 (aac)
我该怎么做? MATLAB中有函数吗?
一个简单的(不一定是最优的)解决方案如下:
digits = sum(x >= '0' & x <= '9');
chars = sum((x >= 'A' & x <= 'Z') | (x >= 'a' & x <= 'z'));
您可以使用正则表达式来完成。例如:
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]'));
是的,有一个内置函数,isstrprop
. It tells you which characters are within the given range, in your case 'digit'
or 'alpha'
. You can then use nnz
获取此类字符的数量:
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
我在单元格中有一个字符串,例如 '5a5ac66'
。我想计算该字符串中的数字和字符数。
'5a5ac66'
= 4 位数字 (5566) 和 3 个字符 (aac)
我该怎么做? MATLAB中有函数吗?
一个简单的(不一定是最优的)解决方案如下:
digits = sum(x >= '0' & x <= '9');
chars = sum((x >= 'A' & x <= 'Z') | (x >= 'a' & x <= 'z'));
您可以使用正则表达式来完成。例如:
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]'));
是的,有一个内置函数,isstrprop
. It tells you which characters are within the given range, in your case 'digit'
or 'alpha'
. You can then use nnz
获取此类字符的数量:
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