【问题标题】:How to split a string into sub strings of n length?如何将字符串拆分为长度为 n 的子字符串?
【发布时间】:2019-05-08 10:29:55
【问题描述】:

如何在 Matlab 中将字符串拆分为长度为 n 的子数组?

例如。

输入:"ABCDEFGHIJKL",子数组长度为 3

输出:{ABC}, {DEF}, {GHI}, {JKL}

【问题讨论】:

    标签: string matlab split


    【解决方案1】:

    如果字符串长度不是n的倍数,您可能需要一个循环或arrayfun

    x = 'ABCDEFGHIJK'; % length 11
    n = 3;
    result = arrayfun(@(k) x(k:min(k+n-1, end)), 1:n:numel(x), 'UniformOutput', false)
    

    或者,也可以使用accumarray

    x = 'ABCDEFGHIJK';
    n = 3;
    result = accumarray(floor((0:numel(x)-1).'/n)+1, x, [], @(t) {t.'}).';
    

    在这个例子中,以上任何一个都给出了,

    result =
      1×4 cell array
        {'ABC'}    {'DEF'}    {'GHI'}    {'JK'}
    

    【讨论】:

    • 非常感谢!这是一篇非常详细的帖子,对我的用例来说非常棒!感谢您的帮助:)
    • @Snel12 很高兴我能帮上忙 :-)
    【解决方案2】:

    正则表达式可以在这里完成工作:

    str = 'abcdefgh'
    exp = '.{1,3}' %the regular expression (get all the group of 3 char, if number of char left < 3, take the rest)
    res = regexp(str,exp,'match')
    

    给:

    res =
      1×3 cell array
        {'abc'}    {'def'}    {'gh'}
    

    如果你只想匹配 3 个字符的组:

    exp = '.{3}' %this will output {'abc'} {'def'} but no {'gh'}
    

    【讨论】:

    • 好主意!非常干净的方法
    【解决方案3】:

    应该这样做:)

    string = cellstr(reshape(string, 3, [])')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      相关资源
      最近更新 更多