用Matlab按字符数拆分字符串

4

在Matlab中是否有任何内置函数可以通过字符数来截取字符串并将其作为单元数组或其他形式返回。例如,如果调用A = some_function(string, 3):

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

或者我需要使用循环吗?
谢谢。
2个回答

6

一种更为优雅(我个人认为)的替代方案是使用regexp

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

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

示例

>> regexp('1234567890', '\w{1,3}', 'match')

ans = 
    '123'    '456'    '789'    '0' 

3

可能稍微有点长:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接