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 <https://github.com/esp8266/arduino/pull/5690>. 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).

String(const char *cstr)
String(const char *cstr, size_t length)
String(const String &str)
String(flash_string_t pstr, int length = -1)
String(String &&rval)
String(StringSumHelper &&rval)
String(char c)
String(unsigned char, unsigned char base = 10)
String(int, unsigned char base = 10)
String(unsigned int, unsigned char base = 10)
String(long, unsigned char base = 10)
String(long long, unsigned char base = 10)
String(unsigned long, unsigned char base = 10)
String(unsigned long long, unsigned char base = 10)
String(float, unsigned char decimalPlaces = 2)
String(double, unsigned char decimalPlaces = 2)

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).

String &operator=(const String &rhs)
String &operator=(const char *cstr)

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.

String &operator=(String &&rval)
String &operator=(StringSumHelper &&rval)

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 unsucessful.

Return Value
  • bool: true on success, false on failure

bool concat(const String &str)
bool concat(const FlashString &fstr)
bool concat(const char *cstr)
bool concat(const char *cstr, size_t length)
bool concat(char c)
bool concat(unsigned char num)
bool concat(int num)
bool concat(unsigned int num)
bool concat(long num)
bool concat(long long num)
bool concat(unsigned long num)
bool concat(unsigned long long num)
bool concat(float num)
bool concat(double num)

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)

String &operator+=(const String &rhs)
String &operator+=(const FlashString &rhs)
String &operator+=(const char *cstr)
String &operator+=(char c)
String &operator+=(unsigned char num)
String &operator+=(int num)
String &operator+=(unsigned int num)
String &operator+=(long num)
String &operator+=(long long num)
String &operator+=(unsigned long num)
String &operator+=(unsigned long long num)
String &operator+=(float num)
String &operator+=(double num)

Comparison methods

Works with String and ‘c’ string

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

Return Value
  • int: Returns < 0 if String is lexically before the argument, > 0 if after or 0 if the same

int compareTo(const char *cstr, size_t length) const
int compareTo(const String &s) const

Test for equality

Compares content byte-for-byte using binary comparison

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

Return Value
  • bool: Returns true if strings are identical

bool equals(const String &s) const
bool equals(const char *cstr) const
bool equals(const char *cstr, size_t length) const
bool equals(const FlashString &fstr) const

Equality operator ==

Return Value
  • bool: true if Strings are identical

bool operator==(const String &rhs) const
bool operator==(const char *cstr) const
bool operator==(const FlashString &fstr) const

In-equality operator !=

Return Value
  • bool: Returns true if strings are not identical

bool operator!=(const String &rhs) const
bool operator!=(const char *cstr) const

Comparison operators

bool operator<(const String &rhs) const
bool operator>(const String &rhs) const
bool operator<=(const String &rhs) const
bool operator>=(const String &rhs) const

Test for equality, without case-sensitivity

null strings are treated as empty.

Return Value
  • bool: true if strings are considered the same

bool equalsIgnoreCase(const char *cstr) const
bool equalsIgnoreCase(const char *cstr, size_t length) const
bool equalsIgnoreCase(const String &s2) const
bool equalsIgnoreCase(const FlashString &fstr) const

Array operators

If index is invalid, returns NUL \0

char operator[](size_t index) const
char &operator[](size_t index)

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.
Return Value
  • int: Index if found, -1 if not found

int indexOf(char ch, size_t fromIndex = 0) const
int indexOf(const char *s2_buf, size_t fromIndex, size_t s2_len) const
int indexOf(const char *s2_buf, size_t fromIndex = 0) const
int indexOf(const String &s2, size_t fromIndex = 0) const

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.
Return Value
  • int: Index if found, -1 if not found

int lastIndexOf(char ch) const
int lastIndexOf(char ch, size_t fromIndex) const
int lastIndexOf(const String &s2) const
int lastIndexOf(const String &s2, size_t fromIndex) const
int lastIndexOf(const char *s2_buf, size_t fromIndex, size_t s2_len) const

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).

Parameters
  • from: Index of first character to retrieve
  • 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);

String substring(size_t from, size_t to) const
String substring(size_t from) const

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.

Return Value
  • 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.

void replace(char find, char replace)
bool replace(const String &find, const String &replace)
bool replace(const char *find_buf, size_t find_len, const char *replace_buf, size_t replace_len)

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
Parameters
  • index: Index of the first character to remove
  • count: Number of characters to remove

void remove(size_t index)
void remove(size_t index, size_t count)

Public Functions

String()

Default constructor.

Note
Creates a null String which evaluates to false.

~String(void)
void setString(const char *cstr, int length = -1)
void setString(flash_string_t pstr, int length = -1)
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 Value
  • 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 Value
  • true: on success, false on failure

size_t length(void) const

Obtain the String length in characters, excluding NUL terminator.

operator StringIfHelperType() const

Provides safe bool() operator.

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

bool startsWith(const String &prefix) const

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

Parameters
  • prefix:
Return Value
  • 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 Value
  • bool: true on match

bool endsWith(const String &suffix) const

Compare the end of a String.

Parameters
  • suffix:
Return Value
  • bool: true on match

char charAt(size_t index) const

Obtain the character at the given index.

Note
If index is invalid, returns NUL \0
Parameters
  • index:
Return Value
  • 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 Value
  • unsigned: number of bytes copied, excluding nul terminator

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

Read contents of String into a buffer.

See
See getBytes()

const char *c_str() const

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

Return Value
  • const: char* Always valid, even for a null string

char *begin()

Get a modifiable pointer to String content.

Note
If String is NUL, returns nullptr.

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.

const char *begin() const
const char *end() const
void toLowerCase(void)

Convert the entire String content to lower case.

void toUpperCase(void)

Convert the entire String content to upper case.

void trim(void)

Remove all leading and trailing whitespace characters from the String.

long toInt(void) const
float toFloat(void) const

Public Members

PtrBuf ptr
SsoBuf sso

Public Static Attributes

const String nullstr

A null string evaluates to false.

const String empty

An empty string evaluates to true.

constexpr size_t SSO_CAPACITY = STRING_OBJECT_SIZE - 2

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

Friends

StringSumHelper &operator+(const StringSumHelper &lhs, const String &rhs)
StringSumHelper &operator+(const StringSumHelper &lhs, const char *cstr)
StringSumHelper &operator+(const StringSumHelper &lhs, char c)
StringSumHelper &operator+(const StringSumHelper &lhs, unsigned char num)
StringSumHelper &operator+(const StringSumHelper &lhs, int num)
StringSumHelper &operator+(const StringSumHelper &lhs, unsigned int num)
StringSumHelper &operator+(const StringSumHelper &lhs, long num)
StringSumHelper &operator+(const StringSumHelper &lhs, unsigned long num)
StringSumHelper &operator+(const StringSumHelper &lhs, unsigned long long num)
StringSumHelper &operator+(const StringSumHelper &lhs, float num)
StringSumHelper &operator+(const StringSumHelper &lhs, double num)