Language Reference (001-198) (061-080)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Code

Here's a working example of several different concatenation examples :

/*
Adding Strings together

Examples of how to add strings together


You can also add several different data types to string, as shown here:

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringAdditionOperator

This example code is in the public domain.


*/

// declare three strings:


String stringOne, stringTwo, stringThree;

void setup() {
// initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

stringOne = String("You added ");


stringTwo = String("this string");
stringThree = String();
// send an intro:
Serial.println("\n\nAdding strings together (concatenation):");
Serial.println();
}

void loop() {
// adding a constant integer to a string:
stringThree = stringOne + 123;
Serial.println(stringThree); // prints "You added 123"

// adding a constant long interger to a string:


stringThree = stringOne + 123456789;
Serial.println(stringThree); // prints "You added 123456789"
// adding a constant character to a string:
stringThree = stringOne + 'A';
Serial.println(stringThree); // prints "You added A"

// adding a constant string to a string:


stringThree = stringOne + "abc";
Serial.println(stringThree); // prints "You added abc"

stringThree = stringOne + stringTwo;


Serial.println(stringThree); // prints "You added this string"

// adding a variable integer to a string:


int sensorValue = analogRead(A0);
stringOne = "Sensor value: ";
stringThree = stringOne + sensorValue;
Serial.println(stringThree); // prints "Sensor Value: 401" or whatever value analogRead(A0)
has

// adding a variable long integer to a string:


long currentTime = millis();
stringOne = "millis() value: ";
stringThree = stringOne + millis();
Serial.println(stringThree); // prints "The millis: 345345" or whatever value currentTime has

// do nothing while true:


while (true);
}

StringIndexOf

String indexOf() and lastIndexOf() Method

The String object indexOf() method gives you the ability to search for the first instance of a
particular character value in a String. You can also look for the first instance of the character
after a given offset. The lastIndexOf() method lets you do the same things from the end of a
String.

String stringOne = "<HTML><HEAD><BODY>";

int firstClosingBracket = stringOne.indexOf('>');

In this case, firstClosingBracket equals 5, because the first > character is at position 5 in the String
(counting the first character as 0). If you want to get the second closing bracket, you can use the
fact that you know the position of the first one, and search from firstClosingBracket + 1 as the
offset, like so:

stringOne = "<HTML><HEAD><BODY>";

int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );

The result would be 11, the position of the closing bracket for the HEAD tag.

If you want to search from the end of the String, you can use the lastIndexOf() method instead.
This function returns the position of the last occurrence of a given character.

stringOne = "<HTML><HEAD><BODY>";

int lastOpeningBracket = stringOne.lastIndexOf('<');

In this case, lastOpeningBracket equals 12, the position of the < for the BODY tag. If you want the
opening bracket for the HEAD tag, it would be at stringOne.lastIndexOf('<', lastOpeningBracket
-1), or 6.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
/*
String indexOf() and lastIndexOf() functions

Examples of how to evaluate, look for, and replace characters in a String


created 27 July 2010
modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringIndexOf

This example code is in the public domain.


*/

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// send an intro:
Serial.println("\n\nString indexOf() and lastIndexOf() functions:");
Serial.println();
}

void loop() {
// indexOf() returns the position (i.e. index) of a particular character
// in a string. For example, if you were parsing HTML tags, you could use it:
String stringOne = "<HTML><HEAD><BODY>";
int firstClosingBracket = stringOne.indexOf('>');
Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);

stringOne = "<HTML><HEAD><BODY>";
int secondOpeningBracket = firstClosingBracket + 1;
int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket);
Serial.println("The index of the second > in the string " + stringOne + " is
" + secondClosingBracket);

// you can also use indexOf() to search for Strings:


stringOne = "<HTML><HEAD><BODY>";
int bodyTag = stringOne.indexOf("<BODY>");
Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag);

stringOne = "<UL><LI>item<LI>item<LI>item</UL>";
int firstListItem = stringOne.indexOf("<LI>");
int secondListItem = stringOne.indexOf("<LI>", firstListItem + 1);
Serial.println("The index of the second list tag in the string " + stringOne + " is
" + secondListItem);

// lastIndexOf() gives you the last occurrence of a character or string:


int lastOpeningBracket = stringOne.lastIndexOf('<');
Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket);

int lastListItem = stringOne.lastIndexOf("<LI>");


Serial.println("The index of the last list tag in the string " + stringOne + " is " + lastListItem);

// lastIndexOf() can also search for a string:


stringOne = "<p>Lorem ipsum dolor sit amet</p><p>Ipsem</p><p>Quod</p>";
int lastParagraph = stringOne.lastIndexOf("<p");
int secondLastGraf = stringOne.lastIndexOf("<p", lastParagraph - 1);
Serial.println("The index of the second to last paragraph tag " + stringOne + " is
" + secondLastGraf);

// do nothing while true:


while (true);
}

StringAppendOperator

Just as you can concatenate Strings with other data objects using the StringAdditionOperator,
you can also use the +=operator and the concat() method to append things to Strings.
The += operator and the concat() method work the same way, it's just a matter of which style
you prefer. The two examples below illustrate both, and result in the same String:

String stringOne = "A long integer: ";

// using += to add a long variable to a string:

stringOne += 123456789;

or

String stringTwo = "A long integer: ";

// using concat() to add a long variable to a string:

stringTwo.concat(123456789);

In both cases, stringOne equals "A long integer: 123456789". Like the + operator, these
operators are handy for assembling longer strings from a combination of data objects.
Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
/*
Appending to Strings using the += operator and concat()

Examples of how to append different data types to strings

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringAppendOperator

This example code is in the public domain.


*/

String stringOne, stringTwo;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

stringOne = String("Sensor ");


stringTwo = String("value");
// send an intro:
Serial.println("\n\nAppending to a string:");
Serial.println();
}

void loop() {
Serial.println(stringOne); // prints "Sensor "

// adding a string to a string:


stringOne += stringTwo;
Serial.println(stringOne); // prints "Sensor value"

// adding a constant string to a string:


stringOne += " for input ";
Serial.println(stringOne); // prints "Sensor value for input"

// adding a constant character to a string:


stringOne += 'A';
Serial.println(stringOne); // prints "Sensor value for input A"

// adding a constant integer to a string:


stringOne += 0;
Serial.println(stringOne); // prints "Sensor value for input A0"

// adding a constant string to a string:


stringOne += ": ";
Serial.println(stringOne); // prints "Sensor value for input"

// adding a variable integer to a string:


stringOne += analogRead(A0);
Serial.println(stringOne); // prints "Sensor value for input A0: 456" or whatever analogRead(A0)
is

Serial.println("\n\nchanging the Strings' values");


stringOne = "A long integer: ";
stringTwo = "The millis(): ";

// adding a constant long integer to a string:


stringOne += 123456789;
Serial.println(stringOne); // prints "A long integer: 123456789"

// using concat() to add a long variable to a string:


stringTwo.concat(millis());
Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is
// do nothing while true:
while (true);
}

StringLengthTrim

String length() and trim() Commands

You can get the length of a Strings using the length() command, or eliminate extra characters
using the trim() command. This example shows you how to use both commands.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
trim() is useful for when you know there are extraneous whitespace characters on the beginning
or the end of a String and you want to get rid of them. Whitespace refers to characters that take
space but aren't seen. It includes the single space (ASCII 32), tab (ASCII 9), vertical tab (ASCII 11),
form feed (ASCII 12), carriage return (ASCII 13), or newline (ASCII 10). The example below shows
a String with whitespace, before and after trimming:

/*
String length() and trim()

Examples of how to use length() and trim() in a String

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringLengthTrim

This example code is in the public domain.


*/

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// send an intro:
Serial.println("\n\nString length() and trim():");
Serial.println();
}

void loop() {
// here's a String with empty spaces at the end (called white space):
String stringOne = "Hello! ";
Serial.print(stringOne);
Serial.print("<--- end of string. Length: ");
Serial.println(stringOne.length());

// trim the white space off the string:


stringOne.trim();
Serial.print(stringOne);
Serial.print("<--- end of trimmed string. Length: ");
Serial.println(stringOne.length());

// do nothing while true:


while (true);
}

StringCaseChanges

The String case change functions allow you to change the case of a String. They work just as their
names imply. toUpperCase() changes the whole string to upper case characters,
and toLowerCase() changes the whole String to lower case characters. Only the characters A to Z
or a to z are affected.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
/*
String Case changes

Examples of how to change the case of a string

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringCaseChanges

This example code is in the public domain.


*/

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// send an intro:
Serial.println("\n\nString case changes:");
Serial.println();
}
void loop() {
// toUpperCase() changes all letters to upper case:
String stringOne = "<html><head><body>";
Serial.println(stringOne);
stringOne.toUpperCase();
Serial.println(stringOne);

// toLowerCase() changes all letters to lower case:


String stringTwo = "</BODY></HTML>";
Serial.println(stringTwo);
stringTwo.toLowerCase();
Serial.println(stringTwo);

// do nothing while true:


while (true);
}

StringReplace

The String replace() function allows you to replace all instances of a given character with another
character. You can also use replace to replace substrings of a string with a different substring.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
Caution: If you try to replace a substring that's more than the whole string itself, nothing will be
replaced. For example:
String stringOne = "<html><head><body>";

String stringTwo = stringOne.replace("<html><head></head><body></body></html>",


"Blah");

In this case, the code will compile, but stringOne will remain unchanged, since the replacement
substring is more than the String itself.

/*
String replace()

Examples of how to replace characters or substrings of a string

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringReplace

This example code is in the public domain.


*/

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// send an intro:
Serial.println("\n\nString replace:\n");
Serial.println();
}

void loop() {
String stringOne = "<html><head><body>";
Serial.println(stringOne);
// replace() changes all instances of one substring with another:
// first, make a copy of th original string:
String stringTwo = stringOne;
// then perform the replacements:
stringTwo.replace("<", "</");
// print the original:
Serial.println("Original string: " + stringOne);
// and print the modified string:
Serial.println("Modified string: " + stringTwo);

// you can also use replace() on single characters:


String normalString = "bookkeeper";
Serial.println("normal: " + normalString);
String leetString = normalString;
leetString.replace('o', '0');
leetString.replace('e', '3');
Serial.println("l33tspeak: " + leetString);

// do nothing while true:


while (true);
}

StringRemove

The remove() method of the String class allows you to remove a specific part of a String. It can be
used with one or two arguments. With one argument, the string from that index to the end is
removed. With two arguments, the first argument is the index of the start of the cut, and the
second argument is the length of the cut.

In this example, the Arduino prints on the serial monitor a full string and the same string with a
portion removed. Both ways of calling the method are demonstrated.

Hardware Required:
Arduino Board
Circuit
There is no circuit for this example, though your Arduino must be connected to your computer
via USB.
Code
/*
Example of the String remove() method

Print on the serial monitor a full string, and then the string with a portion removed.
Both removal methods are demonstrated.

The circuit:
No external components needed.

created 10 Nov 2014


by Arturo Guadalupi

This example code is in the public domain.


*/

String exString = "Hello World!"; // example string

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}

// send an intro:
Serial.println("\n\nString remove() method example");
Serial.println();
}

void loop() {
// Print the initial string
Serial.println("The full string:");
Serial.println(exString);

// Removing from an index through the end


exString.remove(7); // Remove from from index=7 through the end of the string
Serial.println("String after removing from the seventh index through the end");
Serial.println(exString); // Should be just "Hello W"

// Removing only a portion in the middle of a string


exString = "Hello World!";
exString.remove(2, 6); // Remove six characters starting at index=2
Serial.println("String after removing six characters starting at the third position");
Serial.println(exString); // Should be just "Herld!"

Serial.println();
Serial.println();

while(1)
; // no need to do it again
}

StringCharacters

The String functions charAt() and setCharAt() are used to get or set the value of a character at a
given position in a String.

At their simplest, these functions help you search and replace a given character. For example,
the following replaces the colon in a given String with an equals sign:

String reportString = "SensorReading: 456";

int colonPosition = reportString.indexOf(':');

reportString.setCharAt(colonPosition, '=');

Here's an example that checks to see if the first letter of the second word is 'B':

String reportString = "Franklin, Benjamin";

int spacePosition = reportString.indexOf(' ');

if (reportString.charAt(spacePosition + 1) == 'B') {

Serial.println("You might have found the Benjamins.")

Caution: If you try to get the charAt or try to setCharAt() a value that's longer than the String's
length, you'll get unexpected results. If you're not sure, check to see that the position you want
to set or get is less than the string's length using the length() function.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
/*
String charAt() and setCharAt()

Examples of how to get and set characters of a String

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringCharacters

This example code is in the public domain.


*/

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.println("\n\nString charAt() and setCharAt():");


}

void loop() {
// make a string to report a sensor reading:
String reportString = "SensorReading: 456";
Serial.println(reportString);

// the reading's most significant digit is at position 15 in the reportString:


char mostSignificantDigit = reportString.charAt(15);

String message = "Most significant digit of the sensor reading is: ";
Serial.println(message + mostSignificantDigit);

// add blank space:


Serial.println();

// you can alo set the character of a string. Change the : to a = character
reportString.setCharAt(13, '=');
Serial.println(reportString);

// do nothing while true:


while (true);
}

StringStartsWithEndsWith

The String functions startsWith() and endsWith() allow you to check what character or substring
a given String starts or ends with. They're basically special cases of substring.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open..

Code
startsWith() and endsWith() can be used to look for a particular message header, or for a single
character at the end of a String. They can also be used with an offset to look for a substring
starting at a particular position. For example:

stringOne = "HTTP/1.1 200 OK";

if (stringOne.startsWith("200 OK", 9)) {

Serial.println("Got an OK from the server");

This is functionally the same as this:

stringOne = "HTTP/1.1 200 OK";

if (stringOne.substring(9) == "200 OK") {

Serial.println("Got an OK from the server");

Caution: If you look for a position that's outside the range of the string,you'll get unpredictable
results. For example, in the example above stringOne.startsWith("200 OK", 16) wouldn't check
against the String itself, but whatever is in memory just beyond it. For best results, make sure the
index values you use for startsWith and endsWith are between 0 and the String's length().

/*
String startWith() and endsWith()

Examples of how to use startsWith() and endsWith() in a String

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringStartsWithEndsWith

This example code is in the public domain.


*/

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// send an intro:
Serial.println("\n\nString startsWith() and endsWith():");
Serial.println();
}

void loop() {
// startsWith() checks to see if a String starts with a particular substring:
String stringOne = "HTTP/1.1 200 OK";
Serial.println(stringOne);
if (stringOne.startsWith("HTTP/1.1")) {
Serial.println("Server's using http version 1.1");
}

// you can also look for startsWith() at an offset position in the string:
stringOne = "HTTP/1.1 200 OK";
if (stringOne.startsWith("200 OK", 9)) {
Serial.println("Got an OK from the server");
}

// endsWith() checks to see if a String ends with a particular character:


String sensorReading = "sensor = ";
sensorReading += analogRead(A0);
Serial.print(sensorReading);
if (sensorReading.endsWith("0")) {
Serial.println(". This reading is divisible by ten");
} else {
Serial.println(". This reading is not divisible by ten");
}

// do nothing while true:


while (true);
}

StringComparisonOperators

The String comparison operators ==, !=,>, < ,>=, <= , and
the equals() and equalsIgnoreCase()methods allow you to make alphabetic comparisons
between Strings. They're useful for sorting and alphabetizing, among other things.

The operator == and the method equals() perform identically. In other words,
if (stringOne.equals(stringTwo)) {

is identical to

if (stringOne ==stringTwo) {

The ">" (greater than) and "<" (less than) operators evaluate strings in alphabetical order, on the
first character where the two differ. So, for example "a" < "b" and "1" < "2", but "999" >
"1000" because 9 comes after 1.

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.

Hardware Required
Arduino or Genuino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via
USB and the serial monitor window of the Arduino Software (IDE) should be open.

Code
/*
Comparing Strings

Examples of how to compare strings using the comparison operators

created 27 July 2010


modified 2 Apr 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/StringComparisonOperators

You might also like