Counting the amount of each letter in a string

Let’s say I have a string like this:

local String = "ABCOLEHFIOSBIFB"

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.

1 Like

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

string.gsub() returns 2 things - the string with its substitutions, and the amount of substitutions it has made.

print(string.gsub("abcddd", "d", "")) -- "abc", 3

If you don’t care about the substituted string at all, and just want the amount of substitutions, try this:

local subs = select(2, string.gsub("abcddd", "d", ""))
print(subs) -- 3
1 Like

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.

1 Like

This solution worked, thanks!

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)
3 Likes

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