Is there a way to count the number of words in a string via GDscript?

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

I mean, I’m sure this can be done and I can think of a few enormously impractical ways to do it, but is there an easier way i’m just forgetting? I know that you can count a string for the number of characters, but can you count a string with how many words it contains?

For those wondering, I’m trying to make something akin to a word processor that gives a running count of the words written by the user in a certain text. Any ideas?

:bust_in_silhouette: Reply From: Dlean Jeans

You can simply split the string and count the array:

var string = ' The number of words here is 7!  '
var word_count = string.split(' ', false).size()
print(word_count)

Note that the second parameter to split() is allow_empty which removes the spaces on both ends of the string.

:bust_in_silhouette: Reply From: RevonZev

You can also use regex if the string have any white space like space, tab, or newline.

var text := "This is a line\nAnd this is another line"
var regex := RegEx.new()
regex.compile("\\S+")
var result := regex.search_all(text)
print(result.size())