learing:examples:string_start_with_ends_with
String startsWith and endsWith Functions(起始符结束符)
startsWith() 和endsWith()可以检查指定的字符串的开头和结尾的字符是什么。这也是基础的子字符串。
硬件要求
OCROBOT控制器 |
USB线 |
这个例子没有电路图,只需要通过USB线把你的OCROBOT控制器连上电脑,并且打开串口监视器。
ALPHA MEGA328-U核心
硬件
搭建电路
- USB线连接计算机与ALPHA MEGA328-U。
代码
startsWith() 和 endsWith() 用来寻找特别的信息头,或者在字符串末尾寻找单个字符。也可以用这个开头字符来寻找在某个特别的位置开始的子字符串。 例如
stringOne = "HTTP/1.1 200 OK"; if (stringOne.startsWith("200 OK", 9)) { Serial.println("Got an OK from the server"); }
和这个一样的功能
stringOne = "HTTP/1.1 200 OK"; if (stringOne.substring(9) == "200 OK") { Serial.println("Got an OK from the server"); }
注意,如果你寻找的范围超出了字符串长度,就会发生不可预料的错误。例如上面的例子,stringOne.startsWith(“200 OK”, 16)不会核对字符串,但是在内存中已经溢出了。为了得到较好的结果,确保索引值在0和字符串长度之间。
/* String startWith() and endsWith() */ void setup() { // 串口 Serial.begin(9600); // 标题: Serial.println("\n\nString startsWith() and endsWith():"); Serial.println(); } void loop() { // startsWith() 检查字符串是否以子字符串开头 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"); } // 也可以在字符串的一个特定的位置寻找 stringOne = "HTTP/1.1 200 OK"; if (stringOne.startsWith("200 OK", 9)) { Serial.println("Got an OK from the server"); } // endsWith()检查字符串是否以特定的字符结束 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"); } // 循环: while (true); }
learing/examples/string_start_with_ends_with.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1