Getting a random word from within a string

Finding a random word in a string
Hey, everybody, I have been trying my best to make a script for finding a random word in a string.

So I wanted to make a script that can find a random word from a string

example.

local RandomString = (“I am wanting to choose a random word”)

So it would pick a random word from that string.

You can use string.spit() like this

local str = "Hey dude how are you doing?"
local strSplitted = str:split(" ") --Returns a table with all the words seperated by a space
print(strSplitted[math.random(1, #strSplitted)]
3 Likes

You can try this:

local words = {}

for word in RandomString:gmatch("%S+") do
    table.insert(words, word)
end

local randomWord = words[math.random(1, #words)]

gmatch is a function that returns an iterating function with a table of strings matching the pattern specified as its argument. %S+ matches multiple characters that do not include whitespace characters and each word will be the word variable and is inserted into the table.

4 Likes

My first idea would be to split the string based on spaces with the split function (http://lua-users.org/wiki/SplitJoin). Afterwards you generate a random number with math.random() and use it to pick in the list.

local RandomString = “I am wanting to choose a random word”
local words = split(RandomString, " ")
local random_word = words[math.random(1, #words)]

EDIT: Looking at the above replies it is smarter to skip the len step alltogether. It shortens the code by 1 line.

2 Likes