String::concat(const char *cstr, unsigned int length) is protected, why?

Many existing network handling libraries use strings described by a char* and a length to pass data to user code. It would be very convenient to convert these to Strings before working with them, but It’s very inefficient because the scope of the function that can do exactly this (String::concat(const char *cstr, unsigned int length)) is protected.

What’s the reason for this? Is there any chance to change this to public?

Not answering your question, but questioning your use case :wink:

What exactly would you want direct access to that function for?
Why not just use the operator+ which does exactly that?

String str = "someString";
String cat;
char literal[16] = "andThis";

cat = str + "someMore";
cat += literal;

The problem is that these are not null-terminated strings, but they are defined by a char* and a length, and there’s no public function in the String class that can deal with strings defined such way. Of course they can be converted to null-terminated version first, but that requires additional buffers and is inefficient.

Hi @szekelyisz

I think the simple answer is that the Arduino String class does not have that overload.

I do think there is a work-around using the write method with uint8_t* and len. Normally write lets you print into things like Strings and Streams, but I think you can call it directly.

[Corrected type of first arg for write to be uint8_t *]

Thanks @bko, but I don’t really see exactly what you mean. The String class doesn’t derive from anything, so it doesn’t inherit a method named write from anywhere. The only write I found is in the abstract Print class, but I don’t see how that could be useful in this case. Could you be more specific about your idea? Thanks!

Now I see your point and after looking into the code seeing all the other concat() overloads being public it in deed seems unclear why exactly this is not.
Maybe Paul Stoffregen (creator of Teensy) from can clarify that, since that class is based on his code.

Or @mohit could shed light on this from the Particle side.

OK Sorry @szekelyisz, my idea was to use the printable help class but that is also not available, so no go.

I guess would allocate my arrays one bigger and stuff a zero past the end of the data then.

I would also urge you to reconsider using String at all here. Allocating and deallocating large Strings can be problematic for heap fragmentation and cause weird crashes. If you can stuff the zero past the end, then you can just use char* and static allocation.

1 Like