How would I count the number of times A shows up in the string, or how many B’s are in the string? I basically want to check to see if two or more letters in the string are repeating.
First create an empty table for the results, let’s call it repeatingCharacters. The use a for loop with the range from 1 to the length of your string, which can be obtained from string.len(). Then in the for loop, to obtain the character you’re currently iterating over, you can use
local char = str:sub(i, i)
Then do an If statement to check if the char is indexed in the table like this
If not repeatingCharacters[char] then repeatingCharacters[char] = 0 end
To make sure the number is indexed, after that, just do
repeatingCharacters[char] +=1
And continue the loop, when it ends, you will have a table with all the characters and their amounts
Thank you all for your replies. As for this method, is there a way you could inverse it? Where instead of printing abc, it could print “d”? Just checking to confirm if that is possible, I will experiment with everyone’s suggestions.
Here is my final code just in case anyone else is having this issue:
local repeatingcharacters = {}
local char
for i = 1, 5 do
char = string.sub(Word, i,i) -- My word was "hello"
if not repeatingcharacters[char] then
repeatingcharacters[char] = 0
end
repeatingcharacters[char] += 1
end
for i, v in pairs(repeatingcharacters) do
if v > 1 then
char = i
print(i, v) -- prints (L, 2)
end
end
print(char) -- prints (L)