Debian Codegraph @

examples/08.Strings/StringIndexOf/StringIndexOf.ino

raw
1 /*
2 String indexOf() and lastIndexOf() functions
3
4 Examples of how to evaluate, look for, and replace characters in a String
5
6 created 27 Jul 2010
7 modified 2 Apr 2012
8 by Tom Igoe
9
10 This example code is in the public domain.
11
12 https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringIndexOf
13 */
14
15 void setup() {
16 // Open serial communications and wait for port to open:
17 Serial.begin(9600);
18 while (!Serial) {
19 ; // wait for serial port to connect. Needed for native USB port only
20 }
21
22 // send an intro:
23 Serial.println("\n\nString indexOf() and lastIndexOf() functions:");
24 Serial.println();
25 }
26
27 void loop() {
28 // indexOf() returns the position (i.e. index) of a particular character in a
29 // String. For example, if you were parsing HTML tags, you could use it:
30 String stringOne = "<HTML><HEAD><BODY>";
31 int firstClosingBracket = stringOne.indexOf('>');
32 Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);
33
34 stringOne = "<HTML><HEAD><BODY>";
35 int secondOpeningBracket = firstClosingBracket + 1;
36 int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket);
37 Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket);
38
39 // you can also use indexOf() to search for Strings:
40 stringOne = "<HTML><HEAD><BODY>";
41 int bodyTag = stringOne.indexOf("<BODY>");
42 Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag);
43
44 stringOne = "<UL><LI>item<LI>item<LI>item</UL>";
45 int firstListItem = stringOne.indexOf("<LI>");
46 int secondListItem = stringOne.indexOf("<LI>", firstListItem + 1);
47 Serial.println("The index of the second list tag in the string " + stringOne + " is " + secondListItem);
48
49 // lastIndexOf() gives you the last occurrence of a character or string:
50 int lastOpeningBracket = stringOne.lastIndexOf('<');
51 Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket);
52
53 int lastListItem = stringOne.lastIndexOf("<LI>");
54 Serial.println("The index of the last list tag in the string " + stringOne + " is " + lastListItem);
55
56
57 // lastIndexOf() can also search for a string:
58 stringOne = "<p>Lorem ipsum dolor sit amet</p><p>Ipsem</p><p>Quod</p>";
59 int lastParagraph = stringOne.lastIndexOf("<p");
60 int secondLastGraf = stringOne.lastIndexOf("<p", lastParagraph - 1);
61 Serial.println("The index of the second to last paragraph tag " + stringOne + " is " + secondLastGraf);
62
63 // do nothing while true:
64 while (true);
65 }