Arduino自带字符串示例汇总

String示例

1. String Character Analysis

In this example we use the operators that allow us to recognise the type of character we are dealing with. It is useful to check if a character is ASCII, or is upper case, or numeric, or it is a punctuation mark and so forth. The options available cover a variety of situations and this is demonstrated in the sketch below. Every character sent to the board through the serial monitor of the Arduino Software (IDE) is analysed by the sketch that returns all the information it was able to find. A single character may trigger more than one condition and therefore you may get multiple answers for a single entry.

The available operators are:

  • isAlphaNumeric() it’s alphanumeric
  • isAlpha() it’s alphabetic
  • isAscii() it’s ASCII
  • isWhitespace() it’s whitespace
  • isControl() it’s a control character
  • isDigit() it’s a numeric digit
  • isGraph() it’s a printable character that’s not whitespace
  • isLowerCase() it’s lower case
  • isPrintable() it’s printable
  • isPunct() it’s punctuation
  • isSpace() it’s a space character
  • isUpperCase() it’s upper case
  • isHexadecimalDigit() it’s a valid hexadecimaldigit (i.e. 0 - 9, a - F, or A - F)
/*
  Character analysis operators

  Examples using the character analysis operators.
  Send any byte and the sketch will tell you about it.

  created 29 Nov 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/CharacterAnalysis
*/

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("send any byte and I'll tell you everything I can about it");
  Serial.println();
}

void loop() {
  // get any incoming bytes:
  if (Serial.available() > 0) {
    int thisChar = Serial.read();

    // say what was sent:
    Serial.print("You sent me: \'");
    Serial.write(thisChar);
    Serial.print("\'  ASCII Value: ");
    Serial.println(thisChar);

    // analyze what was sent:
    if (isAlphaNumeric(thisChar)) {
      Serial.println("it's alphanumeric");
    }
    if (isAlpha(thisChar)) {
      Serial.println("it's alphabetic");
    }
    if (isAscii(thisChar)) {
      Serial.println("it's ASCII");
    }
    if (isWhitespace(thisChar)) {
      Serial.println("it's whitespace");
    }
    if (isControl(thisChar)) {
      Serial.println("it's a control character");
    }
    if (isDigit(thisChar)) {
      Serial.println("it's a numeric digit");
    }
    if (isGraph(thisChar)) {
      Serial.println("it's a printable character that's not whitespace");
    }
    if (isLowerCase(thisChar)) {
      Serial.println("it's lower case");
    }
    if (isPrintable(thisChar)) {
      Serial.println("it's printable");
    }
    if (isPunct(thisChar)) {
      Serial.println("it's punctuation");
    }
    if (isSpace(thisChar)) {
      Serial.println("it's a space character");
    }
    if (isUpperCase(thisChar)) {
      Serial.println("it's upper case");
    }
    if (isHexadecimalDigit(thisChar)) {
      Serial.println("it's a valid hexadecimaldigit (i.e. 0 - 9, a - F, or A - F)");
    }

    // add some space and ask for another byte:
    Serial.println();
    Serial.println("Give me another byte:");
    Serial.println();
  }
}

2. String Addition Operator

You can add Strings together in a variety of ways. This is called concatenation and it results in the original String being longer by the length of the String or character array with which you concatenate it. The + operator allows you to combine a String with another String, with a constant character array, an ASCII representation of a constant or variable number, or a constant character.

// adding a constant integer to a string:
stringThree =  stringOne + 123;
// adding a constant long integer to a string:
stringThree = stringOne + 123456789;
// adding a constant character to a string:
stringThree =  stringOne + 'A';
// adding a constant string to a string:
stringThree =  stringOne +  "abc";
// adding two Strings together:
stringThree = stringOne + stringTwo;

You can also use the + operator to add the results of a function to a String, if the function returns one of the allowed data types mentioned above. For example,

stringThree = stringOne + millis();

This is allowable since the millis() function returns a long integer, which can be added to a String. You could also do this:

stringThree = stringOne + analogRead(A0);

because analogRead() returns an integer. String concatenation can be very useful when you need to display a combination of values and the descriptions of those values into one String to display via serial communication, on an LCD display, over an Ethernet connection, or anywhere that Strings are useful.

Caution: You should be careful about concatenating multiple variable types on the same line, as you may get unexpected results. For example:

int sensorValue = analogRead(A0);
String stringOne = "Sensor value: ";
String stringThree = stringOne + sensorValue;
Serial.println(stringThree);

results in “Sensor Value: 402” or whatever the analogRead() result is, but

int sensorValue = analogRead(A0);
String stringThree = "Sensor value: " + sensorValue;
Serial.println(stringThree);

gives unpredictable results because stringThree never got an initial value before you started concatenating different data types.

Here’s another example where improper initialization will cause errors:

Serial.println("I want " + analogRead(A0) + " donuts");

This won’t compile because the compiler doesn’t handle the operator precedence correctly. On the other hand, the following will compile, but it won’t run as expected:

int sensorValue = analogRead(A0);
String stringThree = "I want " + sensorValue;
Serial.println(stringThree  + " donuts");

It doesn’t run correctly for the same reason as before: stringThree never got an initial value before you started concatenating different data types.

For best results, initialize your Strings before you concatenate them.

/*
  Adding Strings together

  Examples of how to add Strings together
  You can also add several different data types to String, as shown here:

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/StringAdditionOperator
*/

// declare three Strings:
String stringOne, stringTwo, stringThree;

void setup() {
  // initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  stringOne = String("You added ");
  stringTwo = String("this string");
  stringThree = String();
  // send an intro:
  Serial.println("\n\nAdding Strings together (concatenation):");
  Serial.println();
}

void loop() {
  // adding a constant integer to a String:
  stringThree =  stringOne + 123;
  Serial.println(stringThree);    // prints "You added 123"

  // adding a constant long integer to a String:
  stringThree = stringOne + 123456789;
  Serial.println(stringThree);    // prints "You added 123456789"

  // adding a constant character to a String:
  stringThree =  stringOne + 'A';
  Serial.println(stringThree);    // prints "You added A"

  // adding a constant string to a String:
  stringThree =  stringOne +  "abc";
  Serial.println(stringThree);    // prints "You added abc"

  stringThree = stringOne + stringTwo;
  Serial.println(stringThree);    // prints "You added this string"

  // adding a variable integer to a String:
  int sensorValue = analogRead(A0);
  stringOne = "Sensor value: ";
  stringThree = stringOne  + sensorValue;
  Serial.println(stringThree);    // prints "Sensor Value: 401" or whatever value analogRead(A0) has

  // adding a variable long integer to a String:
  stringOne = "millis() value: ";
  stringThree = stringOne + millis();
  Serial.println(stringThree);    // prints "The millis: 345345" or whatever value millis() has

  // do nothing while true:
  while (true);
}

3. String Appending Operators

Just as you can concatenate Strings with other data objects using the StringAdditionOperator, you can also use the += operator and the concat() method to append things to Strings. The += operator and the concat() method work the same way, it’s just a matter of which style you prefer. The two examples below illustrate both, and result in the same String:

String stringOne = "A long integer: ";
// using += to add a long variable to a string:
stringOne += 123456789;

or

String stringTwo = "A long integer: ";
// using concat() to add a long variable to a string:
stringTwo.concat(123456789);

In both cases, stringOne equals “A long integer: 123456789”. Like the + operator, these operators are handy for assembling longer strings from a combination of data objects.

/*
  Appending to Strings using the += operator and concat()

  Examples of how to append different data types to Strings

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringAppendOperator
*/

String stringOne, stringTwo;

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
  }

  stringOne = String("Sensor ");
  stringTwo = String("value");
  // send an intro:
  Serial.println("\n\nAppending to a String:");
  Serial.println();
}

void loop() {
  Serial.println(stringOne);  // prints  "Sensor "

  // adding a string to a String:
  stringOne += stringTwo;
  Serial.println(stringOne);  // prints "Sensor value"

  // adding a constant string to a String:
  stringOne += " for input ";
  Serial.println(stringOne);  // prints "Sensor value for input"

  // adding a constant character to a String:
  stringOne += 'A';
  Serial.println(stringOne);   // prints "Sensor value for input A"

  // adding a constant integer to a String:
  stringOne += 0;
  Serial.println(stringOne);   // prints "Sensor value for input A0"

  // adding a constant string to a String:
  stringOne += ": ";
  Serial.println(stringOne);  // prints "Sensor value for input"

  // adding a variable integer to a String:
  stringOne += analogRead(A0);
  Serial.println(stringOne);   // prints "Sensor value for input A0: 456" or whatever analogRead(A0) is

  Serial.println("\n\nchanging the Strings' values");
  stringOne = "A long integer: ";
  stringTwo = "The millis(): ";

  // adding a constant long integer to a String:
  stringOne += 123456789;
  Serial.println(stringOne);   // prints "A long integer: 123456789"

  // using concat() to add a long variable to a String:
  stringTwo.concat(millis());
  Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is

  // do nothing while true:
  while (true);
}

4. String Case Change Functions

The String case change functions allow you to change the case of a String. They work just as their names imply. toUpperCase() changes the whole string to upper case characters, and toLowerCase() changes the whole String to lower case characters. Only the characters A to Z or a to z are affected.

/*
  String Case changes

  Examples of how to change the case of a String

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringCaseChanges
*/

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 case changes:");
  Serial.println();
}

void loop() {
  // toUpperCase() changes all letters to upper case:
  String stringOne = "<html><head><body>";
  Serial.println(stringOne);
  stringOne.toUpperCase();
  Serial.println(stringOne);

  // toLowerCase() changes all letters to lower case:
  String stringTwo = "</BODY></HTML>";
  Serial.println(stringTwo);
  stringTwo.toLowerCase();
  Serial.println(stringTwo);


  // do nothing while true:
  while (true);
}

5. StringConstructors

/*
  String constructors

  Examples of how to create Strings from other data types

  created 27 Jul 2010
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringConstructors
*/

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 Constructors:");
  Serial.println();
}

void loop() {
  // using a constant String:
  String stringOne = "Hello String";
  Serial.println(stringOne);      // prints "Hello String"

  // converting a constant char into a String:
  stringOne =  String('a');
  Serial.println(stringOne);       // prints "a"

  // converting a constant string into a String object:
  String stringTwo =  String("This is a string");
  Serial.println(stringTwo);      // prints "This is a string"

  // concatenating two strings:
  stringOne =  String(stringTwo + " with more");
  // prints "This is a string with more":
  Serial.println(stringOne);

  // using a constant integer:
  stringOne =  String(13);
  Serial.println(stringOne);      // prints "13"

  // using an int and a base:
  stringOne =  String(analogRead(A0), DEC);
  // prints "453" or whatever the value of analogRead(A0) is
  Serial.println(stringOne);

  // using an int and a base (hexadecimal):
  stringOne =  String(45, HEX);
  // prints "2d", which is the hexadecimal version of decimal 45:
  Serial.println(stringOne);

  // using an int and a base (binary)
  stringOne =  String(255, BIN);
  // prints "11111111" which is the binary value of 255
  Serial.println(stringOne);

  // using a long and a base:
  stringOne =  String(millis(), DEC);
  // prints "123456" or whatever the value of millis() is:
  Serial.println(stringOne);

  // using a float and the right decimal places:
  stringOne = String(5.698, 3);
  Serial.println(stringOne);

  // using a float and less decimal places to use rounding:
  stringOne = String(5.698, 2);
  Serial.println(stringOne);

  // do nothing while true:
  while (true);

}

6. String Comparison Operators

The String comparison operators ==, !=,>, < ,>=, <= , and the equals() and equalsIgnoreCase() methods allow you to make alphabetic comparisons between Strings. They’re useful for sorting and alphabetizing, among other things.

The operator == and the method equals() perform identically. In other words,

if (stringOne.equals(stringTwo)) {

is identical to

if (stringOne ==stringTwo) {

The “>” (greater than) and “<” (less than) operators evaluate strings in alphabetical order, on the first character where the two differ. So, for example "a" < "b" and "1" < "2", but "999" > "1000" because 9 comes after 1.

Caution: String comparison operators can be confusing when you’re comparing numeric strings, because the numbers are treated as strings and not as numbers. If you need to compare numbers, compare them as ints, floats, or longs, and not as Strings.

/*
  Comparing Strings

  Examples of how to compare Strings using the comparison operators

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringComparisonOperators
*/

String stringOne, stringTwo;

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
  }


  stringOne = String("this");
  stringTwo = String("that");
  // send an intro:
  Serial.println("\n\nComparing Strings:");
  Serial.println();

}

void loop() {
  // two Strings equal:
  if (stringOne == "this") {
    Serial.println("StringOne == \"this\"");
  }
  // two Strings not equal:
  if (stringOne != stringTwo) {
    Serial.println(stringOne + " =! " + stringTwo);
  }

  // two Strings not equal (case sensitivity matters):
  stringOne = "This";
  stringTwo = "this";
  if (stringOne != stringTwo) {
    Serial.println(stringOne + " =! " + stringTwo);
  }
  // you can also use equals() to see if two Strings are the same:
  if (stringOne.equals(stringTwo)) {
    Serial.println(stringOne + " equals " + stringTwo);
  } else {
    Serial.println(stringOne + " does not equal " + stringTwo);
  }

  // or perhaps you want to ignore case:
  if (stringOne.equalsIgnoreCase(stringTwo)) {
    Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
  } else {
    Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo);
  }

  // a numeric String compared to the number it represents:
  stringOne = "1";
  int numberOne = 1;
  if (stringOne.toInt() == numberOne) {
    Serial.println(stringOne + " = " + numberOne);
  }



  // two numeric Strings compared:
  stringOne = "2";
  stringTwo = "1";
  if (stringOne >= stringTwo) {
    Serial.println(stringOne + " >= " + stringTwo);
  }

  // comparison operators can be used to compare Strings for alphabetic sorting too:
  stringOne = String("Brown");
  if (stringOne < "Charles") {
    Serial.println(stringOne + " < Charles");
  }

  if (stringOne > "Adams") {
    Serial.println(stringOne + " > Adams");
  }

  if (stringOne <= "Browne") {
    Serial.println(stringOne + " <= Browne");
  }


  if (stringOne >= "Brow") {
    Serial.println(stringOne + " >= Brow");
  }

  // the compareTo() operator also allows you to compare Strings
  // it evaluates on the first character that's different.
  // if the first character of the String you're comparing to comes first in
  // alphanumeric order, then compareTo() is greater than 0:
  stringOne = "Cucumber";
  stringTwo = "Cucuracha";
  if (stringOne.compareTo(stringTwo) < 0) {
    Serial.println(stringOne + " comes before " + stringTwo);
  } else {
    Serial.println(stringOne + " comes after " + stringTwo);
  }

  delay(10000);  // because the next part is a loop:

  // compareTo() is handy when you've got Strings with numbers in them too:

  while (true) {
    stringOne = "Sensor: ";
    stringTwo = "Sensor: ";

    stringOne += analogRead(A0);
    stringTwo += analogRead(A5);

    if (stringOne.compareTo(stringTwo) < 0) {
      Serial.println(stringOne + " comes before " + stringTwo);
    } else {
      Serial.println(stringOne + " comes after " + stringTwo);

    }
  }
}

7. String indexOf() and lastIndexOf() Method

The String object indexOf() method gives you the ability to search for the first instance of a particular character value in a String. You can also look for the first instance of the character after a given offset. The lastIndexOf() method lets you do the same things from the end of a String.

String stringOne = "<HTML><HEAD><BODY>";
int firstClosingBracket = stringOne.indexOf('>');

In this case, firstClosingBracket equals 5, because the first > character is at position 5 in the String (counting the first character as 0). If you want to get the second closing bracket, you can use the fact that you know the position of the first one, and search from firstClosingBracket + 1 as the offset, like so:

stringOne = "<HTML><HEAD><BODY>";
int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );

The result would be 11, the position of the closing bracket for the HEAD tag.

If you want to search from the end of the String, you can use the lastIndexOf() method instead. This function returns the position of the last occurrence of a given character.

stringOne = "<HTML><HEAD><BODY>";
int lastOpeningBracket = stringOne.lastIndexOf('<');

In this case, lastOpeningBracket equals 12, the position of the < for the BODY tag. If you want the opening bracket for the HEAD tag, it would be at stringOne.lastIndexOf('<', lastOpeningBracket -1), or 6.

String indexOf() and lastIndexOf() Method
The String object indexOf() method gives you the ability to search for the first instance of a particular character value in a String. You can also look for the first instance of the character after a given offset. The lastIndexOf() method lets you do the same things from the end of a String.

String stringOne = "<HTML><HEAD><BODY>";
int firstClosingBracket = stringOne.indexOf('>');
In this case, firstClosingBracket equals 5, because the first > character is at position 5 in the String (counting the first character as 0). If you want to get the second closing bracket, you can use the fact that you know the position of the first one, and search from firstClosingBracket + 1 as the offset, like so:

stringOne = "<HTML><HEAD><BODY>";
int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );
The result would be 11, the position of the closing bracket for the HEAD tag.

If you want to search from the end of the String, you can use the lastIndexOf() method instead. This function returns the position of the last occurrence of a given character.

stringOne = "<HTML><HEAD><BODY>";
int lastOpeningBracket = stringOne.lastIndexOf('<');
In this case, lastOpeningBracket equals 12, the position of the < for the BODY tag. If you want the opening bracket for the HEAD tag, it would be at stringOne.lastIndexOf('<', lastOpeningBracket -1), or 6.

8. String length() and trim() Commands

You can get the length of a Strings using the length() command, or eliminate extra characters using the trim() command. This example shows you how to use both commands.

Code

trim() is useful for when you know there are extraneous whitespace characters on the beginning or the end of a String and you want to get rid of them. Whitespace refers to characters that take space but aren’t seen. It includes the single space (ASCII 32), tab (ASCII 9), vertical tab (ASCII 11), form feed (ASCII 12), carriage return (ASCII 13), or newline (ASCII 10). The example below shows a String with whitespace, before and after trimming:

/*
  String length() and trim()

  Examples of how to use length() and trim() in a String

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/StringLengthTrim
*/

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 length() and trim():");
  Serial.println();
}

void loop() {
  // here's a String with empty spaces at the end (called white space):
  String stringOne = "Hello!       ";
  Serial.print(stringOne);
  Serial.print("<--- end of string. Length: ");
  Serial.println(stringOne.length());

  // trim the white space off the string:
  stringOne.trim();
  Serial.print(stringOne);
  Serial.print("<--- end of trimmed string. Length: ");
  Serial.println(stringOne.length());

  // do nothing while true:
  while (true);
}

9. String replace Function

The Stringreplace() function allows you to replace all instances of a given character with another character. You can also use replace to replace substrings of a String with a different substring.

Code

Caution: If you try to replace a substring that’s more than the whole String itself, nothing will be replaced. For example:

String stringOne = "<html><head><body>";
String stringTwo = stringOne.replace("<html><head></head><body></body></html>", "Blah");

In this case, the code will compile, but stringOne will remain unchanged, since the replacement substring is more than the String itself.

/*
  String replace()

  Examples of how to replace characters or substrings of a String

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringReplace
*/

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 replace:\n");
  Serial.println();
}

void loop() {
  String stringOne = "<html><head><body>";
  Serial.println(stringOne);
  // replace() changes all instances of one substring with another:
  // first, make a copy of the original string:
  String stringTwo = stringOne;
  // then perform the replacements:
  stringTwo.replace("<", "</");
  // print the original:
  Serial.println("Original string: " + stringOne);
  // and print the modified string:
  Serial.println("Modified string: " + stringTwo);

  // you can also use replace() on single characters:
  String normalString = "bookkeeper";
  Serial.println("normal: " + normalString);
  String leetString = normalString;
  leetString.replace('o', '0');
  leetString.replace('e', '3');
  Serial.println("l33tspeak: " + leetString);

  // do nothing while true:
  while (true);
}

10.String startsWith and endsWith Functions

The String functions startsWith() and endsWith() allow you to check what character or substring a given String starts or ends with. They’re basically special cases of substring.

Code

startsWith() and endsWith() can be used to look for a particular message header, or for a single character at the end of a String. They can also be used with an offset to look for a substring starting at a particular position. For example:

stringOne = "HTTP/1.1 200 OK";
if (stringOne.startsWith("200 OK", 9)) {
Serial.println("Got an OK from the server");
}

This is functionally the same as this:

stringOne = "HTTP/1.1 200 OK";
if (stringOne.substring(9) == "200 OK") {
Serial.println("Got an OK from the server");
}

Caution: If you look for a position that’s outside the range of the string,you’ll get unpredictable results. For example, in the example above stringOne.startsWith(“200 OK”, 16) wouldn’t check against the String itself, but whatever is in memory just beyond it. For best results, make sure the index values you use for startsWith and endsWith are between 0 and the String’s length().

/*
  String startWith() and endsWith()

  Examples of how to use startsWith() and endsWith() in a String

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/StringStartsWithEndsWith
*/

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);
}

11.String substring Function

The String function substring() is closely related to charAt(), startsWith() and endsWith(). It allows you to look for an instance of a particular substring within a given String.

Code

substring() with only one parameter looks for a given substring from the position given to the end of the string. It expects that the substring extends all the way to the end of the String. For example:

String stringOne = "Content-Type: text/html";
// substring(index) looks for the substring from the index position to the end:
if (stringOne.substring(19) == "html") {
}

is true, while

String stringOne = "Content-Type: text/html";
// substring(index) looks for the substring from the index position to the end:
if (stringOne.substring(19) == "htm") {
}

is not true, because there’s an l after the htm in the String.

substring() with two parameters looks for a given substring from the first parameter to the second. For example:

String stringOne = "Content-Type: text/html";
// you can also look for a substring in the middle of a string:
if (stringOne.substring(14,18) == "text") {
}

This looks for the word text from positions 14 through 18 of the String.

Caution: make sure your index values are within the String’s length or you’ll get unpredictable results. This kind of error can be particularly hard to find with the second instance of substring() if the starting position is less than the String’s length, but the ending position isn’t.

/*
  String substring()

  Examples of how to use substring in a String

  created 27 Jul 2010,
  modified 2 Apr 2012
  by Zach Eveland

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringSubstring
*/

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  substring():");
  Serial.println();
}

void loop() {
  // Set up a String:
  String stringOne = "Content-Type: text/html";
  Serial.println(stringOne);

  // substring(index) looks for the substring from the index position to the end:
  if (stringOne.substring(19) == "html") {
    Serial.println("It's an html file");
  }
  // you can also look for a substring in the middle of a string:
  if (stringOne.substring(14, 18) == "text") {
    Serial.println("It's a text-based file");
  }

  // do nothing while true:
  while (true);
}

12. String to Int Function

The toInt() function allows you to convert a String to an integer number.

In this example, the board reads a serial input string until it sees a newline, then converts the string to a number if the characters are digits. Once you’ve uploaded the code to your board, open the Arduino IDE serial monitor, enter some numbers, and press send. The board will repeat these numbers back to you. Observe what happens when a non-numeric character is sent.

/*
  String to Integer conversion

  Reads a serial input string until it sees a newline, then converts the string
  to a number if the characters are digits.

  The circuit:
  - No external components needed.

  created 29 Nov 2010
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringToInt
*/

String inString = "";    // string to hold input

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 toInt():");
  Serial.println();
}

void loop() {
  // Read serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      // convert the incoming byte to a char and add it to the string:
      inString += (char)inChar;
    }
    // if you get a newline, print the string, then the string's value:
    if (inChar == '\n') {
      Serial.print("Value:");
      Serial.println(inString.toInt());
      Serial.print("String: ");
      Serial.println(inString);
      // clear the string for new input:
      inString = "";
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蔚蓝慕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值