3

I use a LCD display to display a not known size of text ( changes over time ). I wish to display it at the center of LCD ( 2X16 ).

I declare:

 char t[16];
 char h[16];
 sprintf(t, "%.1f%cC %.0f%%", temperature,223, humidity);

Now, since I want to add additional data on a specific line and center it, I need to know it size. When using:

sizeof(t)/(sizeof(t[0])

I get 16 which is the size determined and not its actual size.

How can I get the exact number of chars used?

VE7JRO
2,51519 gold badges27 silver badges29 bronze badges
asked Jan 18, 2020 at 20:40

1 Answer 1

7

The function I think you are looking for is strlen - STRing LENgth.

It counts the number of characters in a string up until it finds the "NULL" end of string marker.

Serial.println(strlen(t));
answered Jan 18, 2020 at 20:45
3
  • well my guess was it refers to String only Commented Jan 18, 2020 at 20:54
  • 2
    strlen is for C strings (NULL-terminated character arrays). For String you want String.length(). Commented Jan 18, 2020 at 21:01
  • @Guy.D the code you posted is using char arrays, not String objects. Majenko's answer is what you need, not String.length(). Note that you need to be careful not to overflow your char array. That will cause undefined behavior (read "bugs.") Commented Jan 18, 2020 at 22:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.