String length() and trim() Commands

Get and trim the length of a string.

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.

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.

circuit

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:

1/*
2 String length() and trim()
3
4 Examples of how to use length() and trim() in a String
5
6 created 27 Jul 2010
7 modified 2 Apr 2012
8 by Tom Igoe
9
10 This example code is in the public domain.
11
12 http://www.arduino.cchttps://www.arduino.cc/en/Tutorial/StringLengthTrim
13*/
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 only
20 }
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

Contribute to Arduino

Join the community and suggest improvements to this article via GitHub. Make sure to read out contribution policy before making your pull request.

Missing something?

Check out our store and get what you need to follow this tutorial.