The string.find()
method in Lua accepts two string literals and tries to find one in the other.
For example, there is a string A "This is a good day"
as the main string and another string B "a good"
as the search string. The string.find()
method will search string A to find the string B. When found, like in the case stated, the index of the first and last characters of B as found in A will be returned. For this example, the returned value will be [9, 14]
.
string.find(mainString,searchString)
mainString
: This is the string which will be searched in search of another.searchString
: This is the string that needs to be found in the mainString
.The string.find()
method returns the starting and ending indices of the searchString
in the mainString
.
--declare string variablesmainString1 = "Educative shots on Edpresso"searchString1 = "shots on"--number stringsA = "23556667"B = "35"--find some string in others and display ouputprint(string.find(mainString1,searchString1))print(string.find(A,B))print(string.find("Baple man","lm"))print(string.find("Apple man","le"))
Note: All search string characters must be placed consecutively in the main string for successful searching. For example, in line 13 in the above code, it is
nil
becausel
andm
are not side-by-side in the main string parameter. In line 14, thel
ande
that are indeed side-by-side at the end of wordApple
are returned.
Lines 3–4: We declare variables. These are non-number convertible string values.
Lines 7–8: We declare more variables. These are number convertible string values.
Lines 11–14: We use the string.find()
method to find the second string parameter in the first string parameter.