2
String indexOf() and lastIndexOf() functions
4
Examples of how to evaluate, look for, and replace characters in a String
9
http://arduino.cc/en/Tutorial/StringIndexOf
11
This example code is in the public domain.
16
Serial.println("\n\nString indexOf() and lastIndexOf() functions:");
21
// indexOf() returns the position (i.e. index) of a particular character
22
// in a string. For example, if you were parsing HTML tags, you could use it:
23
String stringOne = "<HTML><HEAD><BODY>";
24
int firstClosingBracket = stringOne.indexOf('>');
25
Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);
27
stringOne = "<HTML><HEAD><BODY>";
28
int secondOpeningBracket = firstClosingBracket + 1;
29
int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket );
30
Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket);
32
// you can also use indexOf() to search for Strings:
33
stringOne = "<HTML><HEAD><BODY>";
34
int bodyTag = stringOne.indexOf("<BODY>");
35
Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag);
37
stringOne = "<UL><LI>item<LI>item<LI>item</UL>";
38
int firstListItem = stringOne.indexOf("<LI>");
39
int secondListItem = stringOne.indexOf("item", firstListItem + 1 );
40
Serial.println("The index of the second list item in the string " + stringOne + " is " + secondClosingBracket);
42
// lastIndexOf() gives you the last occurrence of a character or string:
43
int lastOpeningBracket = stringOne.lastIndexOf('<');
44
Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket);
46
int lastListItem = stringOne.lastIndexOf("<LI>");
47
Serial.println("The index of the last list item in the string " + stringOne + " is " + lastListItem);
50
// lastIndexOf() can also search for a string:
51
stringOne = "<p>Lorem ipsum dolor sit amet</p><p>Ipsem</p><p>Quod</p>";
52
int lastParagraph = stringOne.lastIndexOf("<p");
53
int secondLastGraf = stringOne.lastIndexOf("<p", lastParagraph - 1);
54
Serial.println("The index of the second last paragraph tag " + stringOne + " is " + secondLastGraf);
56
// do nothing while true:
b'\\ No newline at end of file'