释放双眼,带上耳机,听听看~!
字符串indexOf() 和 lastIndexOf() 函数
字符串对象indexOf()函数允许你搜索字符串里的一个特殊字符的第一个例子。你也可以寻找一个补偿后的字符的第一个例子。lastIndexOf()函数使你从字符串后面开始做同样的事。
简介
字符串indexOf() 和 lastIndexOf() 函数
字符串对象indexOf()函数允许你搜索字符串里的一个特殊字符的第一个例子。你也可以寻找一个补偿后的字符的第一个例子。lastIndexOf()函数使你从字符串后面开始做同样的事。
String stringOne = "";
int firstClosingBracket = stringOne.indexOf('>');
在这种情况下,firstClosingBracket等于5,因为第一个“>”字符在字符串的第5位(第一个字符当0数)。如果你想得到第二个最近的同类项,你可以用你知道第一个同类项的位置的事实,然后从firstClosingBracket + 1的位置开始查找,就像这样:
stringOne = "
";int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );
结果是11,位置在跟在HEAD后面。
如果你想从字符串的后面开始搜索,你可以用 lastIndexOf() 函数来代替。这个函数返回一个给定字符最后出现的位置。
stringOne = "
";int lastOpeningBracket = stringOne.lastIndexOf('
这种情况下,lastOpeningBracket等于12,“
硬件要求
Arduino or Genuino 开发板
电路
这个例子不需要连接额外的电路,除了你的开发板需要连接到你的电脑,并且打开Arduino IDE的串口监视器窗口。
样例代码
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 = "
";int firstClosingBracket = stringOne.indexOf('>');
Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);
stringOne = "
";int secondOpeningBracket = firstClosingBracket + 1;
int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket);
Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket);
// you can also use indexOf() to search for Strings:
stringOne = "
";int bodyTag = stringOne.indexOf("
");Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag);
stringOne = "
- item
- item
- item
int firstListItem = stringOne.indexOf("
");int secondListItem = stringOne.indexOf("
", firstListItem + 1);Serial.println("The index of the second list tag in the string " + stringOne + " is " + secondListItem);
// lastIndexOf() gives you the last occurrence of a character or string:
int lastOpeningBracket = stringOne.lastIndexOf('
Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket);
int lastListItem = stringOne.lastIndexOf("
");Serial.println("The index of the last list tag in the string " + stringOne + " is " + lastListItem);
// lastIndexOf() can also search for a string:
stringOne = "
Lorem ipsum dolor sit amet
Ipsem
Quod
";int lastParagraph = stringOne.lastIndexOf("
int secondLastGraf = stringOne.lastIndexOf("
Serial.println("The index of the second to last paragraph tag " + stringOne + " is " + secondLastGraf);
// do nothing while true:
while (true);
}