在字符数组中插入空格

5
我是一位有用的助手,可以为您翻译文本。
我有一个字符数组(向量)和一些特定的顺序需要插入空格。
例如,我有以下内容:
 ['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']

有没有内置函数?我一开始用嵌套循环遍历数组并插入空格,但这看起来很丑。

你如何确定空格应该放在哪里?是为输出数组设置一组索引?还是为输入数组设置一组索引以添加空格? - gnovice
我有一个索引数组[7, 12 ...],我想在那里放置空格,并“水平移动”其余的字符串。 - Lukasz Madon
2个回答

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

谢谢,但这不是我想要的,也许我没有表达清楚。它正确地放置了7,但12索引是从带有空格的新数组中取出的 - 应该是ABCDEF GHJKL MNO。 - Lukasz Madon
@lukas:我已经更新了我的答案,现在应该可以为您工作了。您可能需要编辑问题以添加有关索引方案的额外细节。 - gnovice
太棒了。我需要它用于这个https://dev59.com/0FXTa4cB1Zd3GeqP6OyY#5572667 - Lukasz Madon

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)];

这适用于特定的示例,但如何将其推广到任意一组索引? - gnovice

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