PString Library -- printing to strings

PStrings are extremely lightweight string objects that derive from Print. They are designed to render values into character buffers using the same familiar syntax that Serial and LiquidCrystal etc. provide:

str.print("The temperature is ");
str.println(" degrees.");
// do something with str here

PStrings do not own buffers, but instead manage predefined ones. To create a PString, you pass an existing buffer and its size to the constructor:

char buf[40];
PString str(buf, sizeof(buf));

[u]On-the-fly rendering[/u] If, like many users, you just need a quick-and-dirty way to convert some value to a string, you can use PString's constructors to do it inline. The following examples look like simple function calls, but actually create temporary objects which perform the requested rendering before vanishing:

#define PI 3.14
int voltage = 255;
char buf[40];
PString(buf, 40, PI); 
Serial.print(buf); // prints 3.14
PString(buf, 40, voltage); 
Serial.print(buf); // prints 255
PString(buf, 40, voltage, HEX); // buf now contains "FF"
Serial.print(buf); // prints FF

I posted PString to the playground and also here. Thoughts and suggestions for improvements are welcome.


Wow, thank you for sharing that. I'm pretty new to C and find string handling rather crude or limited after having used some BASIC string commands with the PICAXE chip. This should help somewhat.


Thank you, lefty.

I should point out that while PString does offer some string operations like assignment and concatenation, it is not a full-featured String class. Its primary purpose is to be a vehicle for rendering to buffers.

PString buffers have a fixed length and do not grow as a result of an operation. For example, the code

char buf[10];
PString str(buf, 10, "Hello, ");
str += "world";

results in the truncated (but properly terminated) string "Hello, wo" being written to buf. On the positive side, no PString operation can cause an out-of-memory exception, because there is no memory allocation going on under the covers.