【发布时间】:2016-02-09 20:27:43
【问题描述】:
我在单元格中有一个字符串,例如'5a5ac66'。我想计算该字符串中的数字和字符数。
'5a5ac66'= 4 位数字 (5566) 和 3 个字符 (aac)
我该怎么做? MATLAB中有什么函数吗?
【问题讨论】:
标签: matlab function char counting digits
我在单元格中有一个字符串,例如'5a5ac66'。我想计算该字符串中的数字和字符数。
'5a5ac66'= 4 位数字 (5566) 和 3 个字符 (aac)
我该怎么做? MATLAB中有什么函数吗?
【问题讨论】:
标签: matlab function char counting digits
一个简单(不一定是最佳)的解决方案如下:
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。它告诉您哪些字符在给定范围内,在您的情况下为'digit' 或'alpha'。然后您可以使用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
【讨论】:
isstrprop 可以做到这一点(尽管这完全有道理)