Implement PHP's Strpos () and Strrpos () functions in Lua _lua

Source: Internet
Author: User
Tags lua

To write a LUA implementation of PHP's Strpos () function, find a string at the first occurrence of the specified string position, in fact, Lua also provides us with such a function to use String.find () can be obtained, we still write a simple function, the following code:

Copy Code code as follows:

function Strpos (str, f)
If Str ~= nil and F ~= Nil Then
Return (String.find (str, f))
Else
return Nil
End
End

Test as shown in the following illustration:

Here's a strrpos () function that finds the last occurrence of a string in the specified string, and let's just write the function as follows:

Copy Code code as follows:

function Strrpos (str, f)
If Str ~= nil and F ~= Nil Then
Local T = True
Local offset = 1
Local result = Nil
while (t)
Todo
Local TMP = String.find (str, F, offset)
If TMP ~= Nil Then
offset = offset + 1
result = tmp
Else
T = False
End
End
return result
Else
return Nil
End
End

Test the following diagram (note: If you want to find. Escape is required, use "%.") :

Okay, let's get here today, and we'll continue to implement other function functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.