【发布时间】:2019-05-08 10:29:55
【问题描述】:
如何在 Matlab 中将字符串拆分为长度为 n 的子数组?
例如。
输入:"ABCDEFGHIJKL",子数组长度为 3
输出:{ABC}, {DEF}, {GHI}, {JKL}
【问题讨论】:
如何在 Matlab 中将字符串拆分为长度为 n 的子数组?
例如。
输入:"ABCDEFGHIJKL",子数组长度为 3
输出:{ABC}, {DEF}, {GHI}, {JKL}
【问题讨论】:
如果字符串长度不是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'}
【讨论】:
正则表达式可以在这里完成工作:
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'}
【讨论】:
应该这样做:)
string = cellstr(reshape(string, 3, [])')
【讨论】: