indexOf()可以在字符串里寻找特定字符值的第一个实例。也可以在一个给定的起始端寻找字符。lastIndexOf()同样的是在字符串末尾寻找。
String stringOne = "<HTML><HEAD><BODY>"; int firstClosingBracket = stringOne.indexOf('>');
firstClosingBracket等于5,因为第一个>在字符串第五个位置(第一个字符位置为0).也可以用同样的方法想得到第二个>的位置,从firstClosingBracket + 1作为起始端。例如
stringOne = "<HTML><HEAD><BODY>"; int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );
结果是11,是第二个>的位置
如果想在字符串末尾寻找字符,可以使用lastIndexOf() 这个功能返回最后一个出现的字符位置。
stringOne = “<HTML><HEAD><BODY>”; int lastOpeningBracket = stringOne.lastIndexOf('<');</code>
lastOpeningBracket 等于12,最后一个<的位置。
OCROBOT控制器 |
USB线 |
这个例子没有电路图,只需要通过USB线把你的OCROBOT控制器连上电脑,并且打开串口监视器。
/* String indexOf() and lastIndexOf() functions */ void setup() { //串口通信 Serial.begin(9600); // 标题: Serial.println("\n\nString indexOf() and lastIndexOf() functions:"); Serial.println(); } void loop() { // indexOf() 返回字符串里的字符位置 // 如果你要分析HTML标签,你可以这样 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); // 也可以用indexOf() 查找字符串: 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("item", firstListItem + 1); Serial.println("The index of the second list item in the string " + stringOne + " is " + secondClosingBracket); // lastIndexOf() 返回最后一次字符或字符串出现的位置 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 item in the string " + stringOne + " is " + lastListItem); // lastIndexOf() 也可以查找字符串: 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 last paragraph tag " + stringOne + " is " + secondLastGraf); // 循环: while (true); }