How to Use String length()

This example shows you how to use this command to reply to an input from the Serial Monitor.

You can get the length of Strings using the

length()
command. This example shows you how to use this command to reply to an input from the Arduino Software (IDE) serial monitor. If the input string is too long, the sketch will send a specific message to the user

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

length()
returns the length of a String. There are many occasions when you need this. For example,if you wanted to make sure a String was less than 140 characters, to fit it in a text message, you could do this:

1/*
2
3 String length()
4
5 Examples of how to use length() in a String.
6
7 Open the Serial Monitor and start sending characters to see the results.
8
9 created 1 Aug 2010
10
11 by Tom Igoe
12
13 This example code is in the public domain.
14
15 https://www.arduino.cc/en/Tutorial/StringLengthTrim
16
17*/
18
19String txtMsg = ""; // a string for incoming text
20unsigned int lastStringLength = txtMsg.length(); // previous length of the String
21
22void setup() {
23
24 // Open serial communications and wait for port to open:
25
26 Serial.begin(9600);
27
28 while (!Serial) {
29
30 ; // wait for serial port to connect. Needed for native USB port only
31
32 }
33
34 // send an intro:
35
36 Serial.println("\n\nString length():");
37
38 Serial.println();
39}
40
41void loop() {
42
43 // add any incoming characters to the String:
44
45 while (Serial.available() > 0) {
46
47 char inChar = Serial.read();
48
49 txtMsg += inChar;
50
51 }
52
53 // print the message and a notice if it's changed:
54
55 if (txtMsg.length() != lastStringLength) {
56
57 Serial.println(txtMsg);
58
59 Serial.println(txtMsg.length());
60
61 // if the String's longer than 140 characters, complain:
62
63 if (txtMsg.length() < 140) {
64
65 Serial.println("That's a perfectly acceptable text message");
66
67 } else {
68
69 Serial.println("That's too long for a text message.");
70
71 }
72
73 // note the length for next time through the loop:
74
75 lastStringLength = txtMsg.length();
76
77 }
78}

Last revision 2015/08/27 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.