【问题标题】:function for counting digits and char in string in Matlab R2015Matlab R2015中用于计算字符串中数字和字符的函数
【发布时间】:2016-02-09 20:27:43
【问题描述】:

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

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

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

【问题讨论】:

    标签: matlab function char counting digits


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。有用。你回答的计算负担更少。
    【解决方案2】:

    你可以用正则表达式来做到这一点。例如:

    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】:

    是的,有一个内置函数,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
    

    【讨论】:

    • 这是一个很好的解决方案。它也适用于非西方角色。
    • @AlexFeinman 感谢您的评论!我不知道isstrprop 可以做到这一点(尽管这完全有道理)
    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 2016-10-28
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多