Learn to code

Arduino Home

Lessons 1
Arduino - Getting Started
Lessons 2
Arduino - Basics
Lessons 3
Arduino - Serial Communication
Lessons 4
Arduino - Digital / Analog
Lessons 5
Arduino - Visual Output
Lessons 6
Arduino - Motor Control
Lessons 7
Arduino -LCD Displays
Lessons 8
Arduino -LCD Displays

Understanding strings in Arduino

in Arduino Basics

In the arrays tutorial, we mentioned that strings are used to store text or numbers. You can store/remember text or numbers in two ways. You can use the Arduino’s String Object, or you can use a character string. This tutorial will look at how Strings work and what their function can be in an Arduino sketch. First, we will look at the text String, and in another lesson, we will look at a  character string. Before continuing, let’s look at the difference between string and String.

String object: The word String with an uppercase S refers to the Arduino text capability provided by the Arduino String library. The Arduino String function is explained in this lesson.

Character string: The word string with a lowercase s refers to the group of characters rather than the Arduino String functionality. C-string is simply an array of characters, but it is an array of characters that must obey specific rules. It is terminated by a null-character

String or character string

So, the main difference between a character string and a String is that a character refers to a single character while a String refers to multiple characters.

Furthermore, there is a difference between a character and a string

Character: single letter, punctuation, or symbol with single quotes used to represent the character

String: a string refers to a set of characters and uses double quoters for representation.

With an example, we can clarify what the exact difference is between the String and string. The code below will give the same “output” with different coding lines.

String Object

String Text = "Turn Led On";

Serial.println(Text); 

String Number = String('1');

Serial.println(Number);

Character string / c-string

char Text[] = "Turn Led on";

Serial.println(Text);    // prints "Hans"

char Number[] = {'1'}; 

Serial.println(Number);

Both of the codes above print the same text. However, the method that is used is different. The first example uses the Arduino String functionality, while example 2 is using a character string.

The String function for Arduino. I a lot of beginner tutorials you will see this method for displaying text. That is fine in the beginning, but at a point you will see that using the String object has its limitations.

ASCII Characters

One important element in Strings or strings, is that they contain the Asci character. If you construct a string or String from a number or text, the string / String will contain the ASCCI representation of that number.

This can be quite difficult so let’s explore the ASSCI table and give some examples.

Table 1, ASCII characters

The ASCII table represents the characters and numeric values that correspond to a numeric value.

How does this work in your code?  When you create a String or character string (string) a character string is made with text or numbers. These text and numbers are “converted” into ASCCI characters that is used by you Aruino Board/

This seems a bit awkward, right.

Every time you perform a function with the String object the function will use the String characters’ ASCII values. In other words, using a String is different than using numeric values like integers.

String Constructs

Now that we know something about the different “types” of strings. Let us focus on the String with the uppercase S. In fact. String is a class that gives special functionality to character arrays in Arduino. We already created a string class text in the preface and set it to be equal to  Turn LED On. Text is the String object in this case. By using double quotes “…” we are using the construct constant string, a character array.

With a String conductor, you can format all different types of values or datatype into ASCII characters.

There are multiple versions of construct Strings from different data types (i.e., format them as sequences of characters), including:

Using a constant String,

String Text = "Turn LED On";

A single constant character:

String Character = ('a');

Using a constant integer.

String Number = String (13);

Using floating-point numbers:

String Number = String (4.123, 3);

Reading an analog signal and using it as an integer. The value is saved/encoded in ASCCI and will be stored inside the object Number.

String Number = String (analogRead(pinnumber), DEC);

Basically, you will format different values into ASCII characters with these String constructs. There are also functions in the String class that you can use. Let us look at a couple of these functions

String Functions

There are a couple of handy functions within the string class. One of them is to add Strings together or stack them together. Let us create two Strings that we want to combine with a spacing.

String text1 = "Hello";
String text2 = "friends";
String text3 = text1 + " " + text2;

The code above will add the Strings together and create a new String with the combined text. In the String class, there is also a function for his called concat().

String text1 = "Hello";
String text2= "friends";
text1.concat(" ");
text1.concat(text2);

Let us look at some more functions that you can use with the string object.

Example Code Functions

/*
 Basic_Strings sketch with functions
 */
String text1 = "Hello";
String text2 = " Friends";
String text3; // to be assigned within the sketch
void setup()
{
 Serial.begin(9600);
 Serial.print( text1);
 Serial.print(" is ");
 Serial.print(text1.length());
 Serial.println(" characters long.");
 
 Serial.print("text2 is ");
 Serial.print(text2.length());
 Serial.println(" characters long.");
 
 text1.concat(text2);
 Serial.println("text1 now contains: ");
 Serial.println(text1);

 text3 = text1 + " Friends around the world";
  Serial.println("text3 now contains: ");
 Serial.println(text3);

 Serial.println("The third character in text 2 is:");
 Serial.println(text2.charAt(3)); 

 
}
void loop()
{
}

Serial Monitor Output

Figure 1, screenshot from the output of the example code

String Functions: This sketch creates three variables of type String, called text1, text2, and text3. Variables of type String have built-in capabilities for manipulating text.

Length(): The statement text1.length() returns (provides the value of) the length (number of characters) in the string text1.

Concat(): text1.concat(text2) combines the contents of strings; in this case, it appends the contents of text2 to the end of text1 (concat is short for concatenate). The Serial Monitor will display the following:

charAt(n): this statement show the character at position N. Look carefull in out example, we add a spacing before Friends so the third character is a i.

FunctionDescription
charAt(n)Access a particular character of the String.
compareTo(S2)Compares the String to the given String S2
concat(S2) Returns a new String that is the combination of the String and S2
endsWith(S2) Returns true if the String ends with the characters of S2
equals(S2) Returns true if the String is an exact match for S2 (case-sensitive)
equalsIgnoreCase(S2) Same as equals but is not case-sensitive
getBytes(buffer,len) Copies len(gth) characters into the supplied byte buffer
indexOf(S) Returns the index of the supplied String (or character) or –1 if not found
lastIndexOf(S) Same as indexOf but starts from the end of the String
length()Returns the number of characters in the String
replace(A,B) Replaces all instances of String (or character) A with B
setCharAt(index,c) Stores the character c in the String at the given index
startsWith(S2) Returns true if the String starts with the characters of S2
substring(index) Returns a String with the characters starting from index to the end of the String
substring(index,to) Same as above, but the substring ends at the character location before the ‘to’ position
toCharArray(buffer,len) Copies up o len characters of the String to the supplied buffer
toInt() Returns the integer value of the numeric digits in the String
toLowerCase() Returns a String with all characters converted to lowercase
toUpperCase() Returns a String with all characters converted to uppercase
trim() Returns a String with all leading and trailing whitespace removed

Table 2, all the String Class functions

Caution: String comparison operators can be confusing when you’re comparing numeric strings, because the numbers are treated as strings and not as numbers. If you need to compare numbers, compare them as ints, floats, or longs, and not as Strings.

Again, If you see a line such as the following:

char[] = "This is a character array";

Then you know that there the String class is not used, but the character string (c-string) is used.

Choosing between Strings and C-strings

After knowing what Strings are, why would you ever use a character string, string (lowercase s). It seems that you can do a lot with the String class.

Using string objects also have downfalls. Coding in Arduino Strings is easier than using character strings, but this achieved through complex code in the String Library, which makes more demand on your Arduino.

In a character string, each character is just a byte. So if you got an array with 4 characters there will be 4 bytes used, Or 5 bytes if you count the terminating null-character (more about this in the c-string tutorial). A string object will get more bytes than that since there is much more stuff going on to achieve the same result.

If you use C-string, you control the memory usage: you are allocating a fixed amount of memory and not getting memory leaks. The Arduino sketch will have the same amount of memory available at the beginning as well as at the ending of the program.

However, with c-strings, there is one big issue. C-strings will not prevent you from modifying memory beyond the array’s dimension. So if you allocate memory beyond the bounds of an array, for instance, you could do this in your sketch

              ledPin[3]; // character string with three elements+null terminating character
ledPin[4] = ‘5’; // does this element exist?

Since ledPin[4] does not exist, no one knows where this element leads to. Fur sure, it will make your sketch misbehave. So this will require the coder to ensure that this does not happen.

You could use the String class if you need to work with a lot of text and not create and modify strings repeatedly. If you need to modify the Strings in a loop, which is constantly repeating, you are better of using a character string(c-string).

Therefore, after reading this tutorial on the String object, it is wise to read the lesson about c-strings.

Previous Post
Understanding global and local variables for Arduino
Next Post
Understanding Arduino operators
You must be logged in to post a comment.
Menu