【问题标题】:Splitting string by number of characters matlab按字符数分割字符串matlab
【发布时间】:2013-03-28 20:48:43
【问题描述】:

Matlab 中是否有任何内置函数可以按字符数切割字符串并将其作为元胞数组或其他内容返回。例如如果调用 A = some_function(string, 3):

Input: string = '1234567890'
Output: A = {'123', '456', '789', '0'}

还是我需要使用循环?

谢谢。

【问题讨论】:

    标签: string matlab octave


    【解决方案1】:

    另一种更优雅的解决方案(在我看来)是使用regexp

    A = regexp(str, sprintf('\\w{1,%d}', n), 'match')
    

    其中str 是您的字符串,n 是字符数。

    示例

    >> regexp('1234567890', '\w{1,3}', 'match')
    
    ans = 
        '123'    '456'    '789'    '0' 
    

    【讨论】:

      【解决方案2】:

      可能有点长:

      ns = numel(string);
      n = 3;
      A = cellstr(reshape([string repmat(' ',1,ceil(ns/n)*n-ns)],n,[])')'
      

      【讨论】:

      • 像魅力一样工作。非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多