How to get amount of specific chars/letters from a string? Like "Potato" has 2 "o".

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By The_Black_Chess_King

Like in "M a r c u s" string has 5 spaces, ASCII of space is 32, "Potato" has 2 "o". How we do this?

I tried doing with ASCII and a for loop, couldn’t make it work.

Might be redundant, but this is linked question to my original problem before:

Why is get_visible_characters() does not count spaces? (but, possibly?) -Godot3.2.1 Stable - Archive - Godot Forum

The_Black_Chess_King | 2020-05-06 05:27

:bust_in_silhouette: Reply From: im_not_a_robot

Like you said, a for loop works:

var count = 0
for character in "Potato":
	if character == "o":
		count += 1
print(count)

Or you can use a regex. I recommend learning about regexes if you want to do more advanced string processing.

var regex = RegEx.new()
regex.compile("o")
var count = regex.search_all("Potato").size()
print(count)

I hope this helps!

:bust_in_silhouette: Reply From: RedBlueCarrots

The count() function on strings should work.

e.g:

print(“M a r c u s”.count(" ")) will return and output 5

It’s a lot simpler than you were trying!