MATLAB Answers

How to Add two strings

7 views (last 30 days)
hjo
hjo on 22 May 2020
Commented: Mohammad Sami on 22 May 2020
Hi, I am trying to add two strings:
A = 'a b c d e'
B = '1 2 3 4 5'
if I want to return a value 'a1b2c3d4e5', how should I set this up?

  0 Comments

Sign in to comment.

Accepted Answer

Mohammad Sami
Mohammad Sami on 22 May 2020
For a char array of the same length, you can do as follows.
A = 'abcde';
B = '12345';
C = reshape([A;B],1,[]);

  2 Comments

hjo
hjo on 22 May 2020
whar about they are in different lengths?
Mohammad Sami
Mohammad Sami on 22 May 2020
Perhaps you may want to add some padding to make them the same length
A = 'abcde';
B = '1234567';
pad = ' ';
lA = length(A);
lB = length(B);
switch true
case lA < lB
A = [A repelem(pad,lB-lA)];
case lB < lA
B = [B repelem(pad,lA-lB)];
end
C = reshape([A;B],1,[]);

Sign in to comment.

More Answers (0)

Products