Title pretty much explains it. I believe you can use :gmatch and compare it to a tables with numbers/letters, but I was wondering if there was a more efficient way?
First:
To just get the length of a string str
, you could use either #str
or str:len()
or string.len(str)
.
Let's say you wanted to count how many digits a string contains. We could count them:
function isDigit(s) -- lots of ways to do this: return tostring(s) return ("0123456789"):find(s) return s:match("%d") -- (in reality you would probably just put this line -- into that if -- unless you were doing this -- all over the place) end local str = "1apple2banana3" local count = 0 for i = 1, #str do if isDigit(str:sub(i, i)) then count = count + 1 end end print(count) -- 3
This is a bit long and annoying, though.
Observation: we are counting 1 for each digit character, and ignoring all other characters. Thus, if we had digits
string which was only the digits of str
, then we would just have to find its length:
local str = "1apple2banana3" local digits = str:gsub("%D", "") -- global substitution (find&replace) -- of all not digits ("%D") with nothing (""). print(#digits) -- 3
You can do this with more complicated patterns, too. In general it might sometimes be easier to write what is something rather than what is not (e.g. using "%d"
over "%D"
). In that case we just need to subtract the difference:
local str = "1apple2banana3" local notDigits = str:gsub("%d", "") -- #digits + #notDigits = #str -- #digits = #str - #notDigits print( #str - #notDigits ) -- 3
For other sorts of matches, look up information about string patterns. "%a"
is letters, "%A"
is not letters, etc.
Yes, if you use string.len you can find the number of characters/numbers a string may contain. For example:
str = string.len("I am a string") -- Looking for the length of this string. print(str) ==> 13
Please note that spaces count.
This could be considered as a repeat of my last answer, but string.len should help you.
myString = "THIS IS A STRING WITH A RANDOM NUMBER OF CHARACTERS!!!!!" --This string actually has 56 characters. I counted it, lol. print(string.len(myString))
This script should print 56 in the output. If it puts some other number, then I must've counted wrong, but it should turn out to be 56 (or the actual number of characters in the string).
If I helped you, make sure to hit the Accept Answer button below my character!