Wiring String

Small String Optimisation

The String class is probably the most used class in Arduino and Sming.

Unfortunately it gets the blame for one of the most indidious problems in the embedded world, heap fragmentation.

To alleviate this problem, Sming uses a technique known as Small String Optimisation, which uses the available space inside the String object itself to avoid using the heap for small allocations of 10 characters or fewer.

This was lifted from the Arduino Esp8266 core. Superb work - thank you!

Configuration Variables

STRING_OBJECT_SIZE

minimum: 12 bytes (default) maximum: 128 bytes

Must be an integer multiple of 4 bytes.

This is an experimental feature which lets you increase the size of a String object to reduce heap allocations further. The effect of this will vary depending on your application, but you can see some example figures in Pull Request #1951.

Benefits of increasing STRING_OBJECT_SIZE:

  • Increase code speed

  • Fewer heap allocations

Drawbacks:

  • Increased static memory usage for global/static String objects or embedded within global/static class instances.

  • A String can use SSO or the heap, but not both together, so in heap mode any additional SSO space will remain unused.

Allows the size of a String object to be changed to increase the string length available before the heap is used.

Note

The current implementation uses one byte for a NUL terminator, and another to store the length, so the maximum SSO string length is (STRING_OBJECT_SIZE - 2) characters.

However, the implementation may change so if you need to check the maximum SSO string size in your code, please use String::SSO_CAPACITY.

API Documentation

class String

The String class.

Note that a string object’s default constructor creates an empty string. This is not the same as a null string. A null string evaluates to false, but an empty string evaluates to true.

Small String Optimisation means that heap is only used for strings longer than 10 characters, not including the NUL terminator. This is simply making use of existing storage within the String object.

This length can be increased using STRING_OBJECT_SIZE, but note the additional space remains unused when switching to heap storage for longer Strings.

Subclassed by CStringArray, StringSumHelper

Copy constructors

If the initial value is null or invalid, or if memory allocation fails, the string will be marked as invalid (i.e. “if (s)” will be false).

Copy operators

If the value is null or invalid, or if the memory allocation fails, the String will be marked as invalid (“if (s)” will be false).

Move operators

Move content from one String to another without any heap allocation.

Move operators are automatically selected by the compiler when it is able, such as when returning temporary String objects from functions.

In other situations, use std::move:

String original("A String");
String copy("This is the content for the copy");
copy = std::move(myString);
copy will now contain “A String”, whilst original will be invalidated.

Concatenation methods

Works with built-in types. On failure, the string is left unchanged. If the argument is null or invalid, the concatenation is considered unsuccessful.

retval bool:

true on success, false on failure

Concatenation operators

If there’s not enough memory for the concatenated value, the string will be left unchanged (but this isn’t signalled in any way)

Comparison methods

Works with String

and ‘c’ string

Comparisons are case-sensitive, binary comparison null strings (including cstr == nullptr) are treated as empty.

retval int:

Returns < 0 if String is lexically before the argument, > 0 if after or 0 if the same

Test for equality

Compares content byte-for-byte using binary comparison

null strings (including cstr == nullptr) are treated as empty.

retval bool:

Returns true if strings are identical

Equality operator ==

retval bool:

true if Strings are identical

In-equality operator !=

retval bool:

Returns true if strings are not identical

Test for equality, without case-sensitivity

null strings are treated as empty.

retval bool:

true if strings are considered the same

Array operators

If index is invalid, returns NUL \0

int indexOf(…)

Locate a character or String within another String

.

By default, searches from the beginning of the

String, but can also start from a given index, allowing for the locating of all instances of the character or String.
retval int:

Index if found, -1 if not found

int lastIndexOf(…)

Locate a character or String within another String By default, searches from the end of the String, but can also work backwards from a given index, allowing for the locating of all instances of the character or String.

retval int:

Index if found, -1 if not found

String substring(…)

Get a substring of a String

.

The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring).

param from:

Index of first character to retrieve

param to:

(optional) One-past the ending character to retrieve

If the ending index is omitted, the substring continues to the end of the String.

If you don’t need the original String, consider using remove() instead:

    String original("This is the original string.");
    String sub = original.substring(0, 13);
This produces the same result:
    original.remove(13);

replace(…)

Replace all instances of a given character or substring with another character or substring.

Replacing a single character always succeeds as this is handled in-place.

retval bool:

true on success, false on allocation failure

Where replace is longer than find the String may need to be re-allocated, which could fail. If this happens the method returns false and the String is left unchanged.

remove()

Remove characters from a String

.

If no count is provided then all characters from the given index to the end of the

String are removed.

Note

The String is modified in-situ without any reallocation

param index:

Index of the first character to remove

param count:

Number of characters to remove

Pad string to a minimum length

This is used, for example, when outputting tabular data. The string is modified in-situ to minimise memory reallocations.

Methods may be chained like this::

    Serial << String(value).padLeft(10, '.') << endl;

inline String &padLeft(uint16_t minWidth, char c = ' ')

Insert padding at start of string if length is less than given width.

inline String &padRight(uint16_t minWidth, char c = ' ')

Insert padding at end of string if length is less than given width.

String &pad(int16_t minWidth, char c = ' ')

Pad string if length is less than given width.

Parameters:

width – Left-padded if < 0, right-padded if > 0.

Public Functions

inline String()

Default constructor.

Note

Creates a null String which evaluates to false.

bool reserve(size_t size)

Pre-allocate String memory.

On failure, the String is left unchanged. reserve(0), if successful, will validate an invalid string (i.e., “if (s)” will be true afterwards)

Parameters:

size

Return values:

bool – true on success, false on failure

bool setLength(size_t length)

set the string length accordingly, expanding if necessary

Note

extra characters are undefined

Parameters:

length – required for string (nul terminator additional)

Return values:

true – on success, false on failure

inline size_t length(void) const

Obtain the String length in characters, excluding NUL terminator.

bool setBuffer(const Buffer &buffer)

Set String content using move semantics from external memory buffer.

Note

length MUST be < size - A NUL character is written at this location

Parameters:

buffer – We’ll take ownership of this buffer

Return values:

bool – true on success; on failure, ownership of buffer is not transferred

Buffer getBuffer()

Get String content using move semantics.

Note

String is invalidated by this call. Caller is responsible for buffer memory.

Return values:

Buffer

inline operator StringIfHelperType() const

Provides safe bool() operator.

Evaluates as false if String is null, otherwise evaluates as true

inline bool startsWith(const String &prefix) const

Compare the start of a String Comparison is case-sensitive, must match exactly.

Parameters:

prefix

Return values:

bool – true on match

bool startsWith(const String &prefix, size_t offset) const

Compare a string portion.

mis-named as does not necessarily compare from start

Note

Comparison is case-sensitive, must match exactly

Parameters:
  • prefix

  • offset – Index to start comparison at

Return values:

bool – true on match

bool endsWith(char suffix) const

Compare the end of a String.

Parameters:

suffix

Return values:

bool – true on match

bool endsWith(const String &suffix) const

Compare the end of a String.

Parameters:

suffix

Return values:

bool – true on match

inline char charAt(size_t index) const

Obtain the character at the given index.

Note

If index is invalid, returns NUL \0

Parameters:

index

Return values:

char

void setCharAt(size_t index, char c)

Sets the character at a given index.

Note

If index is invalid, does nothing

Parameters:
  • index

  • c

size_t getBytes(unsigned char *buf, size_t bufsize, size_t index = 0) const

Read contents of a String into a buffer.

Note

Returned data always nul terminated so buffer size needs to take this into account

Parameters:
  • buf – buffer to write data

  • bufsize – size of buffer in bytes

  • index – offset to start

Return values:

unsigned – number of bytes copied, excluding nul terminator

inline void toCharArray(char *buf, size_t bufsize, size_t index = 0) const

Read contents of String into a buffer.

See also

See getBytes()

inline const char *c_str() const

Get a constant (un-modifiable) pointer to String content.

Return values:

const – char* Always valid, even for a null string

inline char *begin()

Get a modifiable pointer to String content.

Note

If String is NUL, returns nullptr.

inline char *end()

Get a modifiable pointer to one-past the end of the String.

Note

Points to the terminating NUL character. If String is NUL, returns nullptr.

void toLowerCase(void)

Convert the entire String content to lower case.

void toUpperCase(void)

Convert the entire String content to upper case.

void trim(const char *set = " \t\n\v\f\r")

Remove all leading and trailing characters from the String.

Parameters:

Set – of characters to remove, defaults to whitespace set

Public Static Attributes

static const String nullstr

A null string evaluates to false.

static const String empty

An empty string evaluates to true.

static constexpr size_t SSO_SIZE = std::max(size_t(STRING_OBJECT_SIZE), sizeof(char*) * 3)

Max chars. (excluding NUL terminator) we can store in SSO mode.

struct Buffer

Used with setBuffer and getBuffer methods.

Public Members

char *data

Allocated using malloc.

size_t size

Size of memory allocation.

size_t length

Length of content, MUST be < size.

using FlashString = FSTR::String

Read-only String class stored in flash memory.