Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert spaces in a string (Matlab)

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' 
like image 579
kgk Avatar asked Jun 09 '26 06:06

kgk


1 Answers

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
like image 68
rayryeng Avatar answered Jun 11 '26 01:06

rayryeng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!