String length() and trim() Commands
Get and trim the length of a string.
You can get the length of a Strings using the
length()Hardware Required
- Arduino Board
Circuit
There is no circuit for this example, though your board must be connected to your computer via USB and the serial monitor window of the Arduino Software (IDE) should be open.
Code
trim()1/*2  String length() and trim()3
4  Examples of how to use length() and trim() in a String5
6  created 27 Jul 20107  modified 2 Apr 20128  by Tom Igoe9
10  This example code is in the public domain.11
12  https://www.arduino.cc/en/Tutorial/StringLengthTrim13*/14
15void setup() {16  // Open serial communications and wait for port to open:17  Serial.begin(9600);18  while (!Serial) {19    ; // wait for serial port to connect. Needed for native USB port only20  }21
22  // send an intro:23  Serial.println("\n\nString length() and trim():");24  Serial.println();25}26
27void loop() {28  // here's a String with empty spaces at the end (called white space):29  String stringOne = "Hello!       ";30  Serial.print(stringOne);31  Serial.print("<--- end of string. Length: ");32  Serial.println(stringOne.length());33
34  // trim the white space off the string:35  stringOne.trim();36  Serial.print(stringOne);37  Serial.print("<--- end of trimmed string. Length: ");38  Serial.println(stringOne.length());39
40  // do nothing while true:41  while (true);42}Learn more
You can find more basic tutorials in the built-in examples section.
You can also explore the language reference, a detailed collection of the Arduino programming language.
Last revision 2015/08/11 by SM
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.
