How do I detect the amount of letters used in a message?

Hello!
I am trying to create a system that detects the amount of characters a player used in a message they typed, and depending on the amount of characters typed (1-10 characters 11-100 characters) a sound selected from a pool of preloaded sounds will play and emit from the player.
The issue is that I do not know how to get the amount of characters used in a message, or how to make the sounds selected actually play from the character.
I have tried looking for answers on this but I could only find things explaining how to play the sound but it only comes from the server, and only how to detect if the player says a certain predetermined keyword instead of detecting it based on characters used.

local rps = game:GetService("ReplicatedStorage")
local sounds = rps.sounds
local soundslist = sounds.Accordion:GetChildren()
game.Players.PlayerAdded:Connect(function (player)
	player.Chatted:Connect(function ()
--i will put the thing that detects the amount of characters used here once i figure it out, then do an if statement for the sounds selected.
		print(soundslist[math.random(1,5)])
-- im getting it to randomly select and print the name of the sound, but i am unsure on how to play the sound and link to the humanoid of the char saying it.
	end)
	
end)

Help is appreciated! :grinning:

You can use the string.len(Text) method to find the amount of characters(spaces/tabs included) of a message.

2 Likes
 string.len()

this string function allows you to find the number of characters in a string.

here’s the full documentation on string functions here:
https://developer.roblox.com/en-us/api-reference/lua-docs/string

1 Like

Alternatively, you can put # before a string if you want a more compact and readable way to do it.

local s = "Hello, world!"

print(#s) -- 13
print(#"Hello, world!") -- 13

Not to mention, the using # is faster than string.len by… 3e-8 seconds. The different is negligible, but I personally prefer using # over string.len as it also works for table and array length checks.

EDIT:

Strings are members of the string class, unsurprisingly. You can call the :len() method on a string variable or a string literal.

local s = "Hello, world!"

print(s:len()) -- 13
print(("Hello, world!"):len()) -- 13

Note that it’s mandatory to use parenthesis around the string literal to access the method. Personally, I wouldn’t use this method as it’s lengthier than the # operator and is significantly less readable.

5 Likes