【问题标题】:Insert white spaces into char array将空格插入 char 数组
【发布时间】:2011-04-06 17:27:34
【问题描述】:

我有字符数组(向量),我想按特定顺序插入空格。

例如我有

 ['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']

有内置功能吗?我从嵌套循环开始迭代数组并插入'',但它看起来很难看。

【问题讨论】:

  • 你如何确定空白应该去哪里? 输出数组的一组索引? 输入数组的一组索引以在后面添加空格?
  • 我有一个索引数组 [7, 12 .... 我想把空白放在那里并“水平移动”字符串的其余部分”

标签: arrays matlab string char


【解决方案1】:

如果您的向量中有要插入空白的索引,您可以执行以下操作:

>> 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

【讨论】:

  • thx 但这不是我想要的,也许我不清楚。它正确放置了 7,但 12 索引取自带有空格的新数组 - 应该是 ABCDEF GHJKL MNO。
  • @lukas:我已经更新了我的答案,所以它现在应该对你有用。您可能应该编辑问题以添加有关您的索引方案的额外详细信息。
  • 太棒了。我需要它stackoverflow.com/questions/5558005/…
【解决方案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)];

【讨论】:

  • 这适用于特定示例,但它如何推广到任意一组索引?
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2014-06-04
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2020-04-14
  • 2021-08-01
  • 1970-01-01
相关资源
最近更新 更多