The C++ library for Arduino offers 24 functions to easily handle character strings. charAt • compareTo • concat • c_str • endsWith • equals • getBytes • indexOf • length • remove • replace • startsWith • setCharAt • subString • reserve • toCharArray • toLowerCase • toUpperCase • trim … These functions are supported by the ESP32-Arduino (ESP-IDF wrapper) framework for ESP32 development boards as well as the SDK for ESP8266 boards.
General remarks
- The index of the first character in a string is at position 0, not 1.
- We may need to manipulate strings with arrays of bytes. 1 character = 1 byte
Quick access to functions
charAt compareTo concat c_str endsWith equals getBytes indexOf length remove replace startsWith setCharAt subString reserve toCharArray toLowerCase toUpperCase trim operators
C++ functions for manipulating strings in Arduino code
All the functions used to manipulate the String are detailed here on the official website of the foundation.
charAt(n) allows to extract the character from a string at position n
Serial.println(string1.charAt(2));
compareTo() Compares two strings. Returned value
- a negative number if myString precedes myString2.
- 0 if the two strings are identical
- a positive number if myString is located after myString2
Serial.println(string1.compareTo(string2));
concat() Concatenates (joins) two strings. The result is copied to the first String
startstring.concat(endstring);
Serial.print(startstring);
It is also possible to concatenate strings using the + = operator like this
String demo = "une";
demo += " chaine ";
demo += "de caractères";
c_str() Converts the contents of a string to a C-type string terminated with a null character ‘\0’ .
endsWith() Tests whether or not a string ends with characters from another string.
Returns true if it is, false otherwise.
The startsWith() function allows you to do the same thing but from the beginning of the chain.
Serial.println(string1.endsWith("manipulation"));
equals() Compare if two strings are the same.
Be careful, the comparison is case sensitive, meaning that you have to be careful with upper and lower case letters. The arduino chain is not equal to the ARDUINO chain .
To not take into account the case, use the function equalsIgnoreCase()
String string1 = "A string to test Arduino string manipulation";
String string2 = "a string to test Arduino string manipulation";
Serial.println(string1.equals(string2)); // return 0, different
Serial.println(string1.equalsIgnoreCase(string2)); // return 1, same string
getBytes(buffer, len) Copy each character of the string into a buffer.
The len size of the buffer must correspond to the number of characters in the string +1 .
String stringtocopy = "ESP8266";
// measure length of the string
int buffer_size = stringtocopy.length();
Serial.printf("Buffer size: %u\n", buffer_size);
// Create a buffer having the same size as the string
byte buffer[buffer_size];
// Copy the contents of the string using the getBytes function
// Attention, you must add 1 to the size of the string so as not to have a NULL character
stringtocopy.getBytes(buffer, buffer_size + 1);
Serial.println("Print buffer with write function");
// Each cell of the buffer is printed one by one using a for loop
for (int i = 0; i < buffer_size; i++) {
Serial.write(buffer[i]);
}
indexOf(val, from) Finds the val of a character or a string. By default, the search starts at the beginning of the chain. Indicate the starting position from to start the search from a specific character.
The indexOf() function returns the position of the first occurrence of the string found and -1 otherwise.
Note, the indexOf() function may return inconsistent result when used directly in another function. You have to go through an intermediate variable to retrieve the index as in the example below
int posString = string1.indexOf("Arduino");
Serial.println("Position of Arduino string " + String(posString));
length() Returns the length of the string, in characters without the end of string character ‘\0’ .
Serial.println(string1.length());
remove(from, n) Remove n characters from the string from the from index. The result is stored in the initial chain.
String demoremove = "hello";
demoremove.remove(2,2);
Serial.println(demoremove); // become "heo"
replace() The function allows to replace all occurrences of a given character / string by another character / string.
string1.replace("Arduino","ESP32");
Serial.println(string1);
To replace only one character, you can also use the setCharAt() function.
startsWith() Test whether the string begins with the string passed as a parameter.
Serial.println(string1.startsWith("A text"));
setCharAt(pos, char) Replaces a character in the string at position with a new character.
String stringtomodify = "hello";
char myChar = 'L';
stringtomodify.setCharAt(2,myChar);
Serial.println(stringtomodify); // return heLlo
substring(from, to) Extracts a portion of the string from the from index to the to character .
Use the indexOf() function to find out the position (the index) of a character or a word in the string.
int posString = string1.indexOf("Arduino");
Serial.println("Position of Arduino string " + String(posString));
// Extract the word Arduino in the string
Serial.println(string1.substring(posString, posString + 7));
reserve() is used to optimize memory by allocating the size of the memory reserved to a variable of type String.
String myString;
myString.reserve(20);
myString = "a ";
myString += "demo ";
myString += "with a string";
Serial.println(myString);
Force uppercase or lowercase, remove empty spaces
toLowerCase() forces all characters in the string to lowercase
toUpperCase() forces all characters in the string to uppercase
trim() removes all spaces at the beginning and end of the string
String Conversion Functions
toCharArray(buffer, len) copies each character of a string to a buffer of size len.
String stringtocopy = "ESP8266";
// Measure string length
int buffer_size = stringtocopy.length();
Serial.printf("Buffer size: %u\n", buffer_size);
// Create a buffer having the same size as the string
byte buffer[buffer_size];
// Copy the contents of the string using the getBytes function
// Attention, you must add 1 to the size of the string so as not to have a NULL character
stringtocopy.getBytes(buffer, buffer_size + 1);
Serial.println("Print buffer with write function");
// Each cell of the buffer is printed one by one using a for loop
for (int i = 0; i < buffer_size; i++) {
Serial.write(buffer[i]);
}
Converting a number stored in a String
Function | Use | Example |
toDouble() | Converting to a double or float variable
For example, the strings “123.45”, “123” and “123fish” are converted to 123.45, 123.00 and 123.00 respectively. The function rounds, for example “123.456” will be rounded to 123.46. Floats only have 6-7 decimal digits of precision, so longer strings may be truncated. |
myString.toDouble() |
toInt() | Converting a string to an integer |
myString.toInt() |
Authorized operators on channels
Operator | use | Example |
[] | Access an element of a buffer |
|
Initialize a buffer |
|
|
+ | Concatenate, join two chains |
|
+ = | Adds a new chain to an existing chain
|
|
== | Comparison | True if the strings are the same |
> | Strictly bigger | Use mathematical comparators to compare two strings
|
< | Strictly smaller | |
> = | Greater or equal | |
<= | Smaller or equal | |
! = | Different |
Upload Arduino code to test functions
Create a new sketch on the Arduino IDE or a new PlatformIO project then paste the following code
#include <Arduino.h>
String string1 = "A text to test Arduino string manipulation";
String string2 = "a text to test Arduino string manipulation";
String startstring = "Welcome to ";
String endstring = "this new tutorial";
#define string3 "A different string to test Arduino string manipulation"
#define SERIAL_SPEED 115200
void setup() {
Serial.begin(SERIAL_SPEED);
Serial.println("===== charAt(n) =====");
Serial.println(string1.charAt(2));
Serial.println("===== compareTo() =====");
Serial.print("Same strings "); Serial.println(string1.compareTo(string2));
Serial.print("Different strings"); Serial.println(string1.compareTo(string3));
Serial.println("===== concat() =====");
startstring.concat(endstring);
Serial.println(startstring);
Serial.println("===== endsWith() =====");
Serial.println(string1.endsWith("manipulation"));
Serial.println("===== equals() / equalsIgnoreCase() =====");
Serial.println(string1.equals(string2));
Serial.println(string1.equalsIgnoreCase(string2));
Serial.println("===== getBytes() =====");
String stringtocopy = "ESP8266";
// mesure la longueur de la chaine
int buffer_size = stringtocopy.length();
Serial.printf("Buffer size: %u\n", buffer_size);
// Cree un buffer ayant la meme taille que la chaine
byte buffer[buffer_size];
// Copie le contenu de la chaine a l'aide de la fonction getBytes
// Attention, il faut ajouter 1 a la taille de la chaine pour ne pas avoir de caractere NULL
stringtocopy.getBytes(buffer, buffer_size + 1);
Serial.println("Print buffer with write function");
// On imprime un a un chaque cellule du buffer a l aide d une boucle for
for (int i = 0; i < buffer_size; i++) {
Serial.write(buffer[i]);
}
Serial.println("");
Serial.println("===== indexOf() =====");
int posString = string1.indexOf("Arduino");
Serial.println("Position of Arduino string " + String(posString));
Serial.println(string1.substring(posString, posString + 7));
Serial.println("===== length() =====");
Serial.println(string1.length());
Serial.println("===== remove() =====");
String demoremove = "hello";
demoremove.remove(2,2);
Serial.println(demoremove); // devient "heo"
Serial.println("===== replace() =====");
string1.replace("Arduino","ESP32");
Serial.println(string1);
Serial.println("===== setCharAt() =====");
String stringtomodify = "hello";
char myChar = 'L';
stringtomodify.setCharAt(2,myChar);
Serial.println(stringtomodify);
Serial.println("===== startsWith() =====");
Serial.println(string1.startsWith("A text"));
Serial.println("===== reserve() =====");
String myString;
myString.reserve(20);
myString = "a ";
myString += "demo ";
myString += "with a string";
Serial.println(myString);
Serial.println("===== toCharArray() =====");
String stringtocopy = "Arduino";
// mesure la longueur de la chaine
int buffer_size = stringtocopy.length();
Serial.printf("Buffer size: %u\n", buffer_size);
// Cree un buffer ayant la meme taille que la chaine
byte buffer[buffer_size];
// Copie le contenu de la chaine a l'aide de la fonction getBytes
// Attention, il faut ajouter 1 a la taille de la chaine pour ne pas avoir de caractere NULL
stringtocopy.getBytes(buffer, buffer_size + 1);
Serial.println("Print buffer with write function");
// On imprime un a un chaque cellule du buffer a l aide d une boucle for
for (int i = 0; i < buffer_size; i++) {
Serial.write(buffer[i]);
}
Serial.println("===== < <= > >= =====");
String first = "abc1234";
String second = "def1234";
Serial.print(" first == second "); Serial.println(first == second); // 0
Serial.print(" first > second "); Serial.println(first > second); // 0
Serial.print(" first >= second "); Serial.println(first >= second); // 0
Serial.print(" first < second "); Serial.println(first > second); // 0
Serial.print(" first <= second "); Serial.println(first <= second); // 1
Serial.print(" first != second "); Serial.println(first != second); // 1
}
void loop() {
}
Open the serial monitor to view the operations on the Arduino Strings
===== charAt(n) =====
t
===== compareTo() =====
Same strings -32
Different strings16
===== concat() =====
Welcome to this new tutorial
===== endsWith() =====
1
===== equals() / equalsIgnoreCase() =====
0
1
===== getBytes() =====
Print buffer
Arduin␀
===== indexOf() =====
Position of Arduino string 15
Arduino
===== length() =====
42
===== remove() =====
heo
===== replace() =====
A text to test ESP32 string manipulation
===== setCharAt() =====
heLlo
===== startsWith() =====
1
===== reserve() =====
a demo with a string
===== toCharArray() =====
Print char buffer
ESP8266===== < <= > >= =====
first == second 0
first > second 0
first >= second 0
first < second 0
first <= second 1
first != second 1
Updates
20/10/2020 Publication of the article
- How to store data on a micro SD card. Arduino code compatible ESP32, ESP8266
- Getting started Arduino. Receive commands from the serial port (ESP32 ESP8266 compatible)
- C++ functions print•println•printf•sprintf for Arduino ESP32 ESP8266. Combine•format → serial port
- C++ String functions. concat•c_srt•indexOf•replace•subString… for Arduino, ESP32, ESP8266
- Get started with the I2C bus on Arduino ESP8266 ESP32. Wire.h library