Insert spaces in a string (Matlab)

你离开我真会死。 提交于 2019-12-20 02:59:20

问题


I have a string

   S='ABACBADECAEF'

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' 

回答1:


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.


Method #1 - Split into cells then use 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, ' ');

We get:

Out_S =

AB AC BA DE CA EF

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

We get:

Out_S =

AB AC BA DE CA EF

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(:).');

We get:

Out_S =

AB AC BA DE CA EF


来源:https://stackoverflow.com/questions/31978601/insert-spaces-in-a-string-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!