在字符串中插入空格(Matlab) [英] Insert spaces in a string (Matlab)

查看:1817
本文介绍了在字符串中插入空格(Matlab)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串

   S='ABACBADECAEF'

如何在该字符串的每2个字符之间插入一个空格.扩展后的输出应为:

How can I insert a space in between each 2 characters in that string. The expexted output should be:

 Out_S= 'AB AC BA DE CA EF' 

推荐答案

有几种方法可以做到这一点.所有这些方法均假定您的字符串长度为偶数.如果您有奇数个字符,则不能将最后一对字符分组为一对,因此下面的任何方法都会给您带来尺寸不匹配或超出范围的错误.

There are a few ways you can do that. All of these methods assume that your string length is even. If you had an odd amount of characters, then the last pair of characters can't be grouped into a pair and so any of the methods below will give you a dimension mismatch or out of bounds error.

第一种方法是将字符串分解为单个单元格,然后通过 strjoin 带有空格:

The first method is to decompose the string into individual cells, then join them via strjoin with spaces:

Scell = mat2cell(S, 1, 2*ones(1,numel(S)/2));
Out_S = strjoin(Scell, ' ');

我们得到:

Out_S =

AB AC BA DE CA EF

方法#2-正则表达式

您可以使用正则表达式计算出每个令牌正好2个字符,然后在每个令牌的末尾插入一个空格,如果末尾恰好有空格,则在末尾删去任何空白:

Method #2 - Regular Expressions

You can use regular expressions to count up exactly 2 characters per token, then insert a space at the end of each token, and trim out any white space at the end if there happen to be spaces at the end:

Out_S = strtrim(regexprep(S, '.{2}', '$0 '));

我们得到:

Out_S =

AB AC BA DE CA EF

方法#3-重塑形状以增加一行空格并重塑形状

您可以调整字符矩阵的形状,使每对字符都是一列,您将插入另一行充满空格的行,然后重新调整形状.我们还会修剪掉所有不必要的空格:

Method #3 - Reshaping adding an extra row of spaces and reshaping back

You can reshape your character matrix so that each pair of characters is a column, you would insert another row full of spaces, then reshape back. We also trim out any unnecessary whitespace:

Sr = reshape(S, 2, []);
Sr(3,:) = 32*ones(1,size(Sr,2));
Out_S = strtrim(Sr(:).');

我们得到:

Out_S =

AB AC BA DE CA EF

这篇关于在字符串中插入空格(Matlab)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆