我有字符的char数组(向量),我想按特定顺序插入空格。
例如我有
['A','B','C','D','E','F','G','H','J','K','L','M','N','O']
带有白色空间索引的矢量
[7 12] % white spaces should be add to 7 and 12 indexes (original string)
并希望拥有
['A','B','C','D','E','F',' ','G','H','J','K', 'L', ' ','M','N','O']
是否有一些内置功能?我开始使用嵌套循环来实现数组和instert'',但它看起来很难看。
答案 0 :(得分:5)
如果您的向量中有索引,您希望插入空白,则可以执行以下操作:
>> str = 'ABCDEFGHJKLMNO'; %# Your string
>> index = [7 12]; %# Indices to insert blanks
>> index = index+(0:numel(index)-1); %# Adjust for adding of blanks
>> nFinal = numel(str)+numel(index); %# New length of result with blanks
>> newstr = blanks(nFinal); %# Initialize the result as blanks
>> newstr(setdiff(1:nFinal,index)) = str %# Fill in the string characters
newstr =
ABCDEF GHJKL MNO
答案 1 :(得分:2)
您想在特定索引处插入空格吗?
chars = ['A','B','C','D','E','F','G','H','J','K','L','M','N','O'];
%insert space after index 6 and after index 10 in chars
charsWithWhitespace = [chars(1:6), ' ', chars(7:10), ' ', chars(11:end)];