Language Reference (001-198) (061-080)
Language Reference (001-198) (061-080)
Language Reference (001-198) (061-080)
/*
Adding Strings together
http://www.arduino.cc/en/Tutorial/StringAdditionOperator
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
}
void loop() {
// adding a constant integer to a string:
stringThree = stringOne + 123;
Serial.println(stringThree); // prints "You added 123"
StringIndexOf
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.
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>";
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>";
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
http://www.arduino.cc/en/Tutorial/StringIndexOf
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);
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);
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:
stringOne += 123456789;
or
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()
http://www.arduino.cc/en/Tutorial/StringAppendOperator
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
}
void loop() {
Serial.println(stringOne); // prints "Sensor "
StringLengthTrim
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()
http://www.arduino.cc/en/Tutorial/StringLengthTrim
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());
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
http://www.arduino.cc/en/Tutorial/StringCaseChanges
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);
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>";
In this case, the code will compile, but stringOne will remain unchanged, since the replacement
substring is more than the String itself.
/*
String replace()
http://www.arduino.cc/en/Tutorial/StringReplace
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);
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.
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);
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:
reportString.setCharAt(colonPosition, '=');
Here's an example that checks to see if the first letter of the second word is 'B':
if (reportString.charAt(spacePosition + 1) == 'B') {
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()
http://www.arduino.cc/en/Tutorial/StringCharacters
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
}
void loop() {
// make a string to report a sensor reading:
String reportString = "SensorReading: 456";
Serial.println(reportString);
String message = "Most significant digit of the sensor reading is: ";
Serial.println(message + mostSignificantDigit);
// you can alo set the character of a string. Change the : to a = character
reportString.setCharAt(13, '=');
Serial.println(reportString);
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:
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()
http://www.arduino.cc/en/Tutorial/StringStartsWithEndsWith
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");
}
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
http://www.arduino.cc/en/Tutorial/StringComparisonOperators