这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版 | |||
learing:examples:string_start_with_ends_with [2017/10/05 03:52] – 弘毅 | learing:examples:string_start_with_ends_with [2023/06/07 04:23] (当前版本) – 外部编辑 127.0.0.1 | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== String startsWith and endsWith Functions(起始符结束符) ====== | ||
+ | | ||
+ | |||
+ | ===== 硬件要求 ===== | ||
+ | |||
+ | |OCROBOT控制器| | ||
+ | |USB线| | ||
+ | |||
+ | 这个例子没有电路图,只需要通过USB线把你的OCROBOT控制器连上电脑,并且打开串口监视器。 | ||
+ | ===== ALPHA MEGA328-U核心 ===== | ||
+ | |||
+ | ==== 硬件 ==== | ||
+ | * [[ocrobot: | ||
+ | |||
+ | ==== 搭建电路 ==== | ||
+ | |||
+ | - USB线连接计算机与ALPHA MEGA328-U。 | ||
+ | ==== 代码 ==== | ||
+ | |||
+ | startsWith() 和 endsWith() 用来寻找特别的信息头,或者在字符串末尾寻找单个字符。也可以用这个开头字符来寻找在某个特别的位置开始的子字符串。 | ||
+ | 例如 | ||
+ | < | ||
+ | stringOne = " | ||
+ | if (stringOne.startsWith(" | ||
+ | Serial.println(" | ||
+ | } | ||
+ | </ | ||
+ | 和这个一样的功能 | ||
+ | <code cpp> | ||
+ | |||
+ | stringOne = " | ||
+ | if (stringOne.substring(9) == "200 OK") { | ||
+ | Serial.println(" | ||
+ | } | ||
+ | </ | ||
+ | 注意,如果你寻找的范围超出了字符串长度,就会发生不可预料的错误。例如上面的例子,stringOne.startsWith(" | ||
+ | <code cpp> | ||
+ | |||
+ | /* | ||
+ | String startWith() and endsWith() | ||
+ | */ | ||
+ | |||
+ | void setup() { | ||
+ | // 串口 | ||
+ | Serial.begin(9600); | ||
+ | // 标题: | ||
+ | Serial.println(" | ||
+ | Serial.println(); | ||
+ | } | ||
+ | |||
+ | void loop() { | ||
+ | // startsWith() 检查字符串是否以子字符串开头 | ||
+ | String stringOne = " | ||
+ | Serial.println(stringOne); | ||
+ | if (stringOne.startsWith(" | ||
+ | Serial.println(" | ||
+ | } | ||
+ | |||
+ | // 也可以在字符串的一个特定的位置寻找 | ||
+ | stringOne = " | ||
+ | if (stringOne.startsWith(" | ||
+ | Serial.println(" | ||
+ | } | ||
+ | |||
+ | // endsWith()检查字符串是否以特定的字符结束 | ||
+ | String sensorReading = " | ||
+ | sensorReading += analogRead(A0); | ||
+ | Serial.print(sensorReading); | ||
+ | if (sensorReading.endsWith(" | ||
+ | Serial.println(" | ||
+ | } else { | ||
+ | Serial.println(" | ||
+ | } | ||
+ | |||
+ | // 循环: | ||
+ | while (true); | ||
+ | }</ |