why is a blank ignored in strcat

1 回表示 (過去 30 日間)
Ross
Ross 2013 年 10 月 15 日
コメント済み: Jos (10584) 2013 年 10 月 15 日
as an example, the following code:
strcat(num2str(1,'%02.0f'), '-', num2str(2), ' ', num2str(3), ':', num2str(4,'% 2.0f'))
produces:
01-23:4
whereas I want:
01-2 3: 4
Seems pretty simple but ... would someone help please?

採用された回答

Jan
Jan 2013 年 10 月 15 日
編集済み: Jan 2013 年 10 月 15 日
'% 2.0f' adds a leading space on demand only, so you want: ' %2.0f'.
But this would be nicer, faster and less confusing:
sprintf('%02.0f-%d %d: % 2.0f', 1, 2, 3, 4)
To get around this ugly space gimmicks, which come from the backward compatibility to times before cell strings have been invented, I'm using a dedicated function to join strings: FEX: CStrCatStr. But this is designed for cell strings and for strings horzcat works sufficiently without deleting spaces smartly.

その他の回答 (2 件)

Friedrich
Friedrich 2013 年 10 月 15 日
Hi,
the doc states:
"For character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form-feed. For cell array inputs, strcat does not remove trailing white space."
So you can use:
strcat({num2str(1,'%02.0f')}, {'-'},{num2str(2)}, {' '}, {num2str(3)}, {':'}, {num2str(4,'% 2.0f')})
or dont use strcat and use []:
[num2str(1,'%02.0f'), '-', num2str(2), ' ', num2str(3), ':', num2str(4,'% 2.0f')]
  4 件のコメント
Image Analyst
Image Analyst 2013 年 10 月 15 日
I was talking to Ross. I know Frederich knows both methods and I agree with you about why Frederich answered that way. I was trying to point Ross towards the method that I find gives me much more control with much less complicated syntax.
Jan
Jan 2013 年 10 月 15 日
@Image Analyst: I've inserted "@Ross" in your comment and have removed by concerning question.

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


Jos (10584)
Jos (10584) 2013 年 10 月 15 日
編集済み: Jos (10584) 2013 年 10 月 15 日
This used to be my workaround for the way strcat handles spaces:
strrep(strcat('AAA', '#SPACE#', 'BBB'),'#SPACE#',' ')
  2 件のコメント
Jan
Jan 2013 年 10 月 15 日
What about: ['AAA', ' ', 'BBB'] ?
Jos (10584)
Jos (10584) 2013 年 10 月 15 日

I should have stressed the word used ...

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by