This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Mackan90096's profile picture

[Question] Getting A Certain Word From A String?

Started by Mackan90096, 01 August 2013 - 02:01 AM
Mackan90096 #1
Posted 01 August 2013 - 04:01 AM
Hi there! I'm wondering if you can get a certain word from a string like get the word 'hello' from 'hello world'. I know you can.. But how?

Thanks. // Mackan90096
Yevano #2
Posted 01 August 2013 - 04:07 AM
I assume you mean you want to find the position of a word in a string. Use string.find(str, pattern) Example:

string.find("hi how are you", "how") => 3 5
Mackan90096 #3
Posted 01 August 2013 - 04:09 AM
Well, not really… I want to check like if you type 'hi there' I want it to check whats after 'hi' …
H4X0RZ #4
Posted 01 August 2013 - 04:29 AM

local function whatsAfterMyWord(text,found)
  local words = {}
  local position = 0
  for _,word in string.gmatch(text,"[^ \t]+") do
    words[#words+1] = word
  end
  for k,v in pairs(words) do
    if v == found then 
      position = k 
    end
  end
  if position == 0 then error("word not found",2) end
  if words[position + 1] == nil then
    error("no word after your input",2)
  end
  return words[position + 1]
end
Should work :)/>/>
It iterates trough all words in the text and saves the position of you entered word. At the end it returns the word after your entered word.
Mackan90096 #5
Posted 01 August 2013 - 04:32 AM

local function whatsAfterMyWord(text,found)
  local words = {}
  local position = 0
  for _,word in string.gmatch(text,"[^ \t]+") do
	words[#words+1] = word
  end
  for k,v in pairs(words) do
	if v == found then
	  position = k
	end
  end
  if position == 0 then error("word not found",2) end
  if words[position + 1] == nil then
	error("no word after your input",2)
  end
  return words[position + 1]
end
Should work :)/>/>
It iterates trough all words in the text and saves the position of you entered word. At the end it returns the word after your entered word.

Thanks!

I'll try it!