Jump to content




How can I search in strings ?


  • You cannot reply to this topic
5 replies to this topic

#1 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 24 April 2013 - 03: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-

#2 Imque

  • Members
  • 134 posts

Posted 24 April 2013 - 03:40 AM

input = read()
if input:lower() == "yes" then
-- do something if yes
else
-- do something if not yes
end

#3 GravityScore

  • Members
  • 796 posts
  • LocationLand of Meh

Posted 24 April 2013 - 03: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 


#4 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 24 April 2013 - 03:51 AM

View PostImque, on 24 April 2013 - 03:40 AM, said:

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


#5 H4X0RZ

  • Members
  • 1,315 posts
  • LocationGermany

Posted 24 April 2013 - 03:58 AM

View PostGravityScore, on 24 April 2013 - 03:50 AM, said:

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 :)

#6 digpoe

  • Members
  • 92 posts

Posted 24 April 2013 - 10:01 AM

View PostFreack100, on 24 April 2013 - 03:58 AM, said:

View PostGravityScore, on 24 April 2013 - 03:50 AM, said:

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.





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users