lua string count occurrence

To count the occurrence of a specific string in Lua, you can use the string.gsub function. This function replaces all occurrences of a given pattern in a string and returns the number of replacements made. Here's how you can do it:

  1. Define the string: Specify the string in which you want to count the occurrences. For example, let's say we have the string str = "Hello, hello, hello".

  2. Define the pattern: Next, define the pattern you want to count. For simplicity, let's say we want to count the occurrence of the word "hello". We can define the pattern as pattern = "hello".

  3. Use string.gsub: Now, you can use the string.gsub function to count the number of occurrences. The gsub function takes three arguments: the string, the pattern, and the replacement. Since we only want to count the occurrences, we can provide an empty string "" as the replacement.

The syntax for string.gsub is string.gsub(string, pattern, replacement). In our example, we can use count = string.gsub(str, pattern, "") to count the occurrences of "hello" in the string.

  1. Get the count: The string.gsub function will return the number of replacements made, which in this case is the count of occurrences of the pattern in the string. You can assign this value to a variable, such as count, to access the count later.

  2. Use the count: You can now use the count variable to perform any further operations or display the result as needed.

Here's a complete example:

str = "Hello, hello, hello"
pattern = "hello"
count = string.gsub(str, pattern, "")
print("Count: " .. count)

In this example, the output will be Count: 3, indicating that the word "hello" appears three times in the string.