Arduino内置教程-字符串-String Start With Ends With
字符串 startsWith 和 endsWith 函数
- 字符串函数startsWith() 和 endsWith()允许你检查一个给定的字符串的开始或者结束是什么字符或者子字符串。他们是子字符串的基本特殊例子。
 
硬件要求
- Arduino or Genuino 开发板
 
电路
- 这个例子不需要连接额外的电路,除了你的开发板需要连接到你的电脑,并且打开Arduino IDE的串口监视器窗口。
 

图由 Fritzing 软件绘制
样例代码
- 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)不能核对字符串本身,但是无论内存里有什么都超过它了。为了最好的结果,确保你用来索引的值(startsWith 和 endsWith)要在0到字符串的length()之间。
 
/*
  String startWith() and endsWith()
 Examples of how to use startsWith() and endsWith() in a String
 created 27 July 2010
 modified 2 Apr 2012
 by Tom Igoe
 http://www.arduino.cc/en/Tutorial/StringStartsWithEndsWith
 This example code is in the public domain.
 */
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 startsWith() and endsWith():");
  Serial.println();
}
void loop() {
  // startsWith() checks to see if a String starts with a particular substring:
  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");
  }
  // you can also look for startsWith() at an offset position in the string:
  stringOne = "HTTP/1.1 200 OK";
  if (stringOne.startsWith("200 OK", 9)) {
    Serial.println("Got an OK from the server");
  }
  // endsWith() checks to see if a String ends with a particular character:
  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");
  }
  // do nothing while true:
  while (true);
}
更多
- String object – 字符串对象的参考
 - CharacterAnalysis - 使用operators来识别对应的特征类型。
 - StringAdditionOperator - 用不同方法把字符串加到一起。
 - StringAppendOperator - 用+=运算符和concat()方法来添加东西到字符串里。
 - StringCaseChanges - 改变字符串的状态。
 - StringCharacters - 在字符串里获得或设置一个指定的字符的值
 - StringComparisonOperators - 按字母排列顺序地比较字符串
 - StringConstructors - 初始化字符串对象
 - StringIndexOf - 寻找在字符串里字符的第一个或最后一个的状态
 - StringLength - 获得和修剪字符串的长度
 - StringLengthTrim - 获得和修剪字符串的长度
 - StringReplace - 替换字符串里的个别字符
 - StringStartsWithEndsWith - 检查一个给定的字符或子串(substrings)的开始或结尾
 - StringSubstring - 在给定的字符串里寻找"phrases"
 - StringToInt - 允许你把字符串转换成整数数字