How to get an NBT string's length?

Story

I am making a chatbot in Minecraft. Players "type" in their messages to the chatbot using a grid of buttons representing numbers, letters, and symbols. Each button press appends a new string to an NBT list. For example, the L button runs the following command:

data modify storage chatbot:main CurrentEntry append value "L"

Once done, the player presses the Submit button, which concatenates all the values in the array into one string, and submits it to the chatbot.

Problem

To reduce processing times, I have decided to institute a rule that messages may only be two hundred fifty-six characters long or less. I need a way to figure out how many items are in the string, and if there are more than 256, set some sort of flag to be detected by the system as too long.

Core question

How do you get the length of an NBT string? Given an NBT string...

Input:{String:"Life is a bowl of cherries"}

can you retrieve the number of characters in the string and output it?

Output:{StringLength:26b}

Notes

  • If your solution requires concatenating or splitting the string, please do also answer the matching question below.

See also

  • Concatenating NBT strings
  • Splitting NBT strings

Solution 1:

Here's something interesting about /data. When you get the value of the tag using /data get ... it returns the value in chat, but it also returns the length of that string. So you can use it in combination with /execute store to store the length. Example:

/execute store result storage minecraft:root Output.StringLength int 1 run data get storage minecraft:root Input.String

Storage object before the command:

root:{Input:{String:"Hello world"}}

Storage object after the command:

root:{Input:{String:"Hello world"}, Output:{StringLength:11}}

This also works with scoreboard objectives.