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

How can I search in strings ?

Started by H4X0RZ, 24 April 2013 - 02:25 AM
H4X0RZ #1
Posted 24 April 2013 - 04:25 AM
Hi com,
I want to make a program (for my os), with them you can "chat". It works good, but my program don't check what I tiped in. Just random came like"Yes", "I don't think so" etc.

Does anybody know how can I search IN the message I wrote?

Thanks for reading
-Freack100-
Imque #2
Posted 24 April 2013 - 04:40 AM
input = read()
if input:lower() == "yes" then
– do something if yes
else
– do something if not yes
end
GravityScore #3
Posted 24 April 2013 - 04:50 AM
Use string.find:

local str = "hello"

print(string.find(str, "h")) -- prints 1, 1, because h starts at the first character, and ends at the first character
print(str:find("he")) -- prints 1, 2, because he starts at the first character, and ends at the second
print(str:find("l")) -- prints 3, 3, because string.find will find the first occurrence 
H4X0RZ #4
Posted 24 April 2013 - 04:51 AM
input = read()
if input:lower() == "yes" then
– do something if yes
else
– do something if not yes
end
thx… But it's not what I want ^_^/>

Pseudocode:

If "hello world" contains "hello" then do something
Else do something else
H4X0RZ #5
Posted 24 April 2013 - 04:58 AM
Use string.find:

local str = "hello"

print(string.find(str, "h")) -- prints 1, 1, because h starts at the first character, and ends at the first character
print(str:find("he")) -- prints 1, 2, because he starts at the first character, and ends at the second
print(str:find("l")) -- prints 3, 3, because string.find will find the first occurrence 
Thx, that's what I want :)/>
digpoe #6
Posted 24 April 2013 - 11:01 AM
Use string.find:

local str = "hello"

print(string.find(str, "h")) -- prints 1, 1, because h starts at the first character, and ends at the first character
print(str:find("he")) -- prints 1, 2, because he starts at the first character, and ends at the second
print(str:find("l")) -- prints 3, 3, because string.find will find the first occurrence
Thx, that's what I want :)/>

You can also use string.match(), which returns whatever you tell it to look for. Example:


local text = "Hello, world!"
print(string.match(text, "Hello") ~= nil)

That code above returns whether the 'text' variable contains 'Hello' in it.