Overview
This example demonstrates how to use startsWith() and endsWith() functions. These return boolean values which indicate if a string STARTS WITH a given set of characters or ENDS WITH.
For example, say we have a string “hello world”. If we were to apply the startsWith() function to this string searching for the word “hell” then the result would true. The same would apply if we were to check with endsWith() except that the result would return false.
Sample Code
/*
String startWith() and endsWith()
Examples of how to use startsWith() and endsWith() in a String
created 27 July 2010
modified 30 Aug 2011
by Tom Igoe
http://arduino.cc/en/Tutorial/StringStartsWithEndsWith
This example code is in the public domain.
*/
void setup() {
Serial.begin(9600);
Serial.println("nnString startsWith() and endsWith():");
}
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);
}
The setup() Function
The setup() function performs two primary tasks.
1. Establish serial communication at a rate of 9600 baud
2. Print a status message serially
The loop() Function
The loop() function does various operations using the startsWith() and endsWith() functions. Once it completes its task it outputs results serially.
Refer to line(s) 25, 31 and 39. We suggest testing this code in your Arduino IDE to see exactly what goes on here for yourself. However, we will explain it.
On line 25 the code checks to see if stringOne starts with “HTTP/1.1″ which it does – therefore the IF body will execute.
On line 31 the code checks to see if stringOne starts with “200 OK” except this time around it uses an offset which starts the string at a different index than 0. In this case – it also evaluates to true therefore the IF body will execute.
Lastly, on line 39 the code uses endsWith() function to determine if a string ends with 0. The result of this operation depends on the sensor reading. Therefore, you will need to connect a sensor to your Arduino compatible board in order to test this code. Alternatively, you could put some arbitrary data to test the code instead of using a sensor.
