Arduino String

From WikiOD

Strings are used to store text. They can be used to display text in the LCD or Arduino IDE serial monitor window. Strings can also be used to store user input. For example, the characters typed by the user on the keyboard connected to the Arduino.

There are two types of strings in Arduino programming:

  • The character array is the same as the character string used in C programming.
  • Arduino strings, it allows us to use string objects in sketches.

In this chapter, we will learn the use of strings, objects and strings in Arduino sketches. At the end of this chapter, you will learn which type of string to use in your sketches.

String character array[edit | edit source]

The first type of string we want to learn is a series of characters of type  char . In the previous chapters, we learned what an array is: a continuous sequence of variables of the same type stored in memory. A string is an array of char variables.

A string is a special array with an extra element at the end of the string, and its value is always 0 (zero). This is called a "null-terminated string".

String character array example[edit | edit source]

This example will show how to create a string and print it to the serial monitor window.

Example:[edit | edit source]

 void setup() {
    char my_str[6]; // an array big enough for a 5 character string
    Serial.begin(9600);
    my_str[0] = 'H'; // the string consists of 5 characters
    my_str[1] = 'e';
    my_str[2] = 'l';
    my_str[3] = 'l';
    my_str[4] = 'o';
    my_str[5] = 0; // 6th array element is a null terminator
    Serial.println(my_str);
 }
 
 void loop() { 
 
 }

The following example shows what a string consists of. A character array with printable characters and 0 as the last element of the array indicates that this is the end of the string. By using Serial.println() and passing the name of the string, the string can be printed to the Arduino IDE serial monitor window.

The same example can be written in a more convenient way, as shown below:

Example:[edit | edit source]

 void setup() {
    char my_str[] = "Hello";
    Serial.begin(9600);
    Serial.println(my_str);
 }
 
 void loop() {
 
 }

In this sketch, the compiler calculates the size of the string array and automatically terminates the string with a null value of 0. An array that is six elements long and consists of five characters followed by a zero is created in exactly the same way as the previous sketch.

Manipulate string array[edit | edit source]

We can change the string array in the sketch, as shown in the figure below.

Example:[edit | edit source]

 void setup() {
    char like[] = "I like coffee and cake"; // create a string
    Serial.begin(9600);
    // (1) print the string
    Serial.println(like);
    // (2) delete part of the string
    like[13] = 0;
    Serial.println(like);
    // (3) substitute a word into the string
    like[13] = ' '; // replace the null terminator with a space
    like[18] = 't'; // insert the new word
    like[19] = 'e';
    like[20] = 'a';
    like[21] = 0; // terminate the string
    Serial.println(like);
 }
 
 void loop() {
 
 }

Result[edit | edit source]

I like coffee and cake
I like coffee
I like coffee and tea

The above sketch works in the following way.

(1) Create and print strings[edit | edit source]

In the sketch given above, a new string is created and then printed out and displayed in the serial monitor window.

(2) Shorten the string[edit | edit source]

Shorten the string by replacing the 14th character in the string with a null-terminated 0. This is the 13th element in the string array counting from 0.

When printing a string, all characters are printed to the new null-terminated 0. The other characters do not disappear; they still exist in memory, and the string array is still the same size. The only difference is that any function that uses strings can only see the string before the first null terminator.

(3) Change the word in the string[edit | edit source]

Finally, the sketch replaces the word "cake" with "tea". It must first replace the null terminator with a space, such as [13], in order to restore the string to its original format.

The new character covers the "cak" of the word "cake" with the word "tea". This is done by overwriting a single character. The "e" of "cake" is replaced with a new null terminating character. The result is that the string actually ends with two null characters, the original character at the end of the string, and a new character that replaces the "e" in " cake ". This makes no difference when printing a new string, because the function that prints the string will stop printing the string characters when it encounters the first null terminating character.

Functions for manipulating string arrays[edit | edit source]

The previous sketch manipulated the string manually by accessing individual characters in the string. In order to manipulate the string array more conveniently, you can write your own function to execute it, or you can use some string functions in the C language library.

The list function for manipulating string arrays is shown below.

The next sketch uses some C string functions.

Example:[edit | edit source]

 void setup() {
    char str[] = "This is my string"; // create a string
    char out_str[40]; // output from string functions placed here
    int num; // general purpose integer
    Serial.begin(9600);
 
    // (1) print the string
    Serial.println(str);
 
    // (2) get the length of the string (excludes null terminator)
    num = strlen(str);
    Serial.print("String length is: ");
    Serial.println(num);
 
    // (3) get the length of the array (includes null terminator)
    num = sizeof(str); // sizeof() is not a C string function
    Serial.print("Size of the array: ");
    Serial.println(num);
 
    // (4) copy a string
    strcpy(out_str, str);
    Serial.println(out_str);
 
    // (5) add a string to the end of a string (append)
    strcat(out_str, " sketch.");
    Serial.println(out_str);
    num = strlen(out_str);
    Serial.print("String length is: ");
    Serial.println(num);
    num = sizeof(out_str);
    Serial.print("Size of the array out_str[]: ");
    Serial.println(num);
 }
 
 void loop() {
 
 }

Result[edit | edit source]

This is my string
String length is: 17
Size of the array: 18
This is my string
This is my string sketch.
String length is: 25
Size of the array out_str[]: 40

The above sketch works in the following way.

(1) Print string[edit | edit source]

The newly created string will be printed to the serial monitor window, as done in the previous sketch.

(2) Get the length of the string[edit | edit source]

The strlen() function is used to obtain the length of a string. The length of the string is only for printable characters, excluding the null terminator.

The string contains 17 characters, so we see 17 characters in the serial monitor window.

(3) Get the length of the array[edit | edit source]

The operator sizeof() is used to get the length of the array containing the string. The length includes the null terminator, so the length is one more than the length of the string.

sizeof() looks like a function, but is technically an operator. It is not part of the C string library, but is used in the sketch to show the difference between array size and string size (or string length).

(4) Copy the string[edit | edit source]

The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies the second string passed to it into the first string. Now, a copy of the string exists in the out_num[] array, but only takes up 18 elements of the array, so there are still 22 free char elements in the array. These free elements can be found at the end of the string in memory.

Copy the string into the array so that we have some extra space in the array for the next part of the sketch, which is to add a string to the end of the string.

(5) Append the string to the string (concatenation)[edit | edit source]

The sketch adds one string to another string, which is called concatenation. This is done using the strcat() function. The strcat() function puts the second string passed to it at the end of the first string passed to it.

After concatenation, print the length of the string to display the new length of the string. Then print the length of the array to show that there is a 25-character string in the 40-element long array.

Remember that a 25-character string actually occupies 26 characters of the array because there is still a null-terminated 0.

Array boundary[edit | edit source]

When working with strings and arrays, it is very important to work within the boundaries of the string or array. In the example sketch, an array of 40 characters in length is created to allocate memory that can be used to manipulate strings.

If the array is too small and we try to copy a string larger than the array, then the string will be copied to the end of the array beyond. The memory beyond the end of the array may contain other important data used in the sketch, but they will be overwritten by the string. If the memory beyond the end of the string is out of range, it may cause the sketch to crash or cause unexpected behavior.