How to EXACTLY count how many letters are in string

I’m attempting to make Dialogues. When the character finished talking, it is supposed to wait a certain time before the next dialogue.

I use task.wait(), around 5 or 8 seconds as max. But I want it to be depending of how many letters the text has.

I attempted to use string.len and #, this is the result with each attempt:

“Red Alert!” has 9 letters including the ! but it printed as 10 due to the space.

local text = "Red Alert!" -- 9
task.wait(#text) / task.wait(string.len(text)) -- 10

How can I make it counting exactly what letters the string contains?

1 Like

Well to get the length of the text. So heres how to do it. I think ofc.

local text = 'Red Alert!'


local Words = string.split(text, ' ')

local TextLength = ''

for _, word in pairs(Words) do
	TextLength = TextLength..word
end

print(TextLength)

print('The finished number result is:'..#TextLength)

Theres probably a better way to do this but, here it i!

4 Likes

Make a list of letters. Then loop through every character of a lowercase version of the string. If it exists in the letter list, count it. If not, ignore it and move on.

(this may not work in lua but it would work in JS)

EDIT: according to another poster, they pretty much have a code version of what I was thinking of. turns out I keep thinking you gotta reinvent the wheel, but you dont, look at how they can just use some percent!

3 Likes

I assume a hacky way would to make a new string and filter out the characters you don’t want with string.gsub(). For example, string.gsub(yourstring, " ", “”), that would replace all spaces.

Another way would be iterating through the whole string and skipping any characters you do not want, while keeping a running count of those you want. (Like oddcraft said)

3 Likes

You need to exclude any spaces or special characters from the count babes, here is how you would go about doing that:

local text = "Red Alert!"
local letterCount = 0

for i = 1, #text do
  local char = text:sub(i, i)
  if char:match("%a") then 
    letterCount = letterCount + 1
  end
end

print(letterCount) 
task.wait(letterCount) 
4 Likes

Didn’t even think of sub and matching like that, I’d personally use this one.

1 Like

Thanks this actually worked! But its taking longer for the next character to speak.

But you gave me an idea how to fix this new problem, thanks anyway!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.