Putting spaces between strings?

I have three different strings and are putting them together in an array. The result is simply the three strings combined. However, I want to put spaces between each string. I tried doing this:
a = 'str1'
b = 'str2'
c = 'str3'
x = [a,'',b,'',c]
but that doesn't do anything so how would I put spaces then?

 採用された回答

Image Analyst
Image Analyst 2013 年 3 月 17 日
編集済み: Image Analyst 2013 年 3 月 17 日

3 投票

Your '' is just a null string - no space was between the quotes - so that's why no space was inserted. I really like using sprintf() for building up strings. A way using sprintf:
x = sprintf('%s %s %s', a, b, c);
Note the spaces in between the %s. That will make spaces in the final output string.

5 件のコメント

Joe
Joe 2013 年 3 月 17 日
I tried that code, but ended up getting an empty array
Image Analyst
Image Analyst 2013 年 3 月 17 日
Joe, you did something wrong. Here, I just copied and pasted my code:
clc;
a = 'str1'
b = 'str2'
c = 'str3'
% sprintf() method:
x = sprintf('%s %s %s', a, b, c)
% Concatenation method:
x = [a, ' ', b, ' ', c]
and now I copy and paste the command window:
a =
str1
b =
str2
c =
str3
x =
str1 str2 str3
x =
str1 str2 str3
You can certainly see that it is not empty. Is your a, b, and c cell arrays, not character strings? What does this say:
>> whos a
Joe
Joe 2013 年 3 月 17 日
Oh I see what was wrong, I got it to work! Thanks for the help!
M. Saim  Riaz
M. Saim Riaz 2016 年 5 月 28 日
Hi Image Analyst! I want the spaces between the characters I stored in an array using a for loop.
for j=1:5
turn(j)='t';
end
It gives this result,
turn =
tttt
How can I insert spaces between these 't's? I tried using this, but it gives error.
for j=1:5
turn(j)='t ';
end
Image Analyst
Image Analyst 2016 年 5 月 28 日
Saim, I'm not sure why you got 4 t's. I got 5. Anyway to put a space after each t, do this:
for j=1:5
turn(j*2-1)='t';
turn(j*2)=' ';
end
turn % Display in command window.

サインインしてコメントする。

その他の回答 (1 件)

Luke Perry
Luke Perry 2018 年 8 月 29 日

0 投票

Image Analyst's code is absolutely correct, but to add on, here is how to fix your original code:
a = 'str1';
b = 'str2';
c = 'str3';
x = [a,' ',b,' ',c]
x =
>>'str1 str2 str3'
notice the '' was turned into ' '. That is, a space was added between the single quotes. I use this method often when using messagebox string definition to easily read what the user will see in side the messagebox, but either answer works. I'm not entirely sure which would necessarily be more correct or efficient.

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

Joe
2013 年 3 月 17 日

回答済み:

2018 年 8 月 29 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by