4

Octave adds spaces with strcat

In Octave I run these commands:

strcat ("hel", " ", "lo") 

I get this result:

ans = hello

Instead of what I expected:

ans = hel lo

strcat to me sounds like "concatenate strings". A space is a valid character, so adding a space should be OK. Matlab has the same behaviour, so it's probably intended.

I find it counter intuitive. Does this behavior makes sense?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335

2 Answers2

4

Hmm. It works how it is defined:

"strcat removes trailing white space in the arguments (except within cell arrays), while cstrcat leaves white space untouched. "

From http://www.gnu.org/software/octave/doc/interpreter/Concatenating-Strings.html

So the question could be: Should this behaviour be changed.

pbhd
  • 4,384
  • 1
  • 20
  • 26
1

strcat takes the input parameters and trims the trailing spaces, but not the leading spaces. if you pass a parameter as one or more spaces, they are collapsed to blank string.

That behavior is a manifestation of how "cellstr" works where spaces at the end are removed.

Work around 1

If you put the space up against the 'lo', it is a leading space and not removed.

strcat ("hel", " lo")

ans = hel lo

Work around 2

use cstrcat instead:

cstrcat("hel", " ", "lo")

ans = hel lo

Work around 3

Use sprintf, can be faster than strcat.

sprintf("%s%s%s\n", "hel", " ", "lo")

ans = hel lo
AcidResin
  • 134
  • 2
  • 12
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335