Inserting a tab character into a string

I am attempting to insert a space into a string. Here is my code:
t1 = 'Control Chart For ';
t2 = '\t';
t3 = num2str(w);
t4 = ' water flow ';
t5 = '\t';
t6 = num2str(o);
t7 = ' oil flow ';
str = strcat(t1, t2, t3, t4, t5, t6, t7);
This should yield:
Control Chart For 5 water flow 3 oil flow
however it yields instead:
Control Chart For\t5 water flow\t3 oil flow
Just adding spaces in the string does not work either and making the string \t instead of '\t' also fails.

Antworten (5)

Andrew Newell
Andrew Newell am 3 Feb. 2011

8 Stimmen

A nicer way of doing it is
str = sprintf('Control Chart For \t %d water flow \t %d oil flow',w,o)

2 Kommentare

Oleg Komarov
Oleg Komarov am 3 Feb. 2011
I would go for this approach, it is more readable the way space chars are handled.
Stephen23
Stephen23 am 13 Feb. 2015
Using sprintf is also faster than concatenating strings.

Melden Sie sich an, um zu kommentieren.

Paulo Silva
Paulo Silva am 3 Feb. 2011

2 Stimmen

char(9) instead of only one string doesn't seem to work, I also tried, sprintf('\t'), this way works:
t1 = 'Control Chart For ';
t3 = [char(9) num2str(w)];
t4 = ' water flow ';
t6 = [char(9) num2str(o)];
t7 = ' oil flow ';
str = strcat(t1,t3, t4, t6, t7)

3 Kommentare

Paulo Silva
Paulo Silva am 3 Feb. 2011
That's why I did this
t3 = [char(9) num2str(w)];
instead of
t2=char(9);
t3 = num2str(w);
Andrew Newell
Andrew Newell am 3 Feb. 2011
Absolutely. And I like your diplomatic way of saying I'm wrong!
Walter Roberson
Walter Roberson am 3 Feb. 2011
strcat does not remove whitespace from cell strings.

Melden Sie sich an, um zu kommentieren.

the cyclist
the cyclist am 3 Feb. 2011

1 Stimme

Are you trying to insert a tab character, or just white space? If the latter, you can concatenate with square brackets:
>> str = [t1, t3, t4, t6, t7]
Then the trailing whitespace in t1, etc, will not be dropped, and you don't need to manually insert the space.
Looks like this syntax works for tab as well:
>> str = [t1, char(9), t2, t3, t4, t5, t6, t7]
Aleksandar Mojsic
Aleksandar Mojsic am 20 Jul. 2014

0 Stimmen

This will work:
str = sprintf([t1, t2, t3, t4, t5, t6, t7])
fernando bordignon
fernando bordignon am 23 Mär. 2016

0 Stimmen

You can also use the tab itself, but you need to disable the "insert white spaces" option at the editor preferences. Another way of doing that would be by copy pasting the tab character from another editor.

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 3 Feb. 2011

Beantwortet:

am 23 Mär. 2016

Community Treasure Hunt

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

Start Hunting!

Translated by