String contains a certain word

Asked

Viewed 392 times

7

I’d like to check if a string contains a certain word.

String = "oi\ntchau\nhi\nbye"

To string is divided by \n (jumps line), I would like to check between each line, if it contains the whole word, I have tried and I have not yet managed.

3 answers

10


You can use the functions match or find to find the string you want. Both return a boolean value indicated by the presence of string

string.match("oi\ntchau\nhi\nbye", "hi")

Documentation match()

string.find("oi\ntchau\nhi\nbye", "hi")

Documentation find()

Both solve your problem if you just want to know whether or not it contains the string sought. The result can be used in a if hassle-free.

If not, you need to be more specific in the question and show what you have already done, and point out what the problem is.

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

6

To find out whether the whole word is in the string, you can use it like this:

procuro = "tchau"
dentrode = "oi\ntchau\nhi\bye"

string.match( "\n" .. dentrode .. "\n", "\n" .. procuro .. "\n" )

Explanation:

  • We use "\n" additional in procuro to search only whole words;

  • Similarly, we add the "\n" in dentrode, because if you search for the whole word and it is at the beginning or end of the string, it will be found in the same way.

2

Possibly so:

--remover todos os /n
local result = string.gsub(s, "n", " ") -- remove line breaks

--Depois procurar as palavras
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.