string.sub()
The string.sub()
function in Lua extracts a substring from a given string. It allows you to specify the starting and optionally the ending positions for the substring. This function is useful for string manipulation and text processing.
Syntax
string.sub(s, start, end_)
Parameters
- Name
s
- Type
- string
- Description
The string from which to extract the substring.
- Name
start
- Type
- number
- Description
The starting position of the substring (1-based index).
- Name
end_
- Type
- number
- Description
The ending position of the substring (1-based index). If omitted, the substring will extend to the end of the string.
Return Value
Returns the extracted substring. If the starting position is greater than the length of the string, an empty string is returned. If the ending position is less than the starting position, it also returns an empty string.
Examples
Example 1: Extracting a Substring
Extract a simple substring from a string.
Example 1
local substring = string.sub("Hello, World!", 1, 5)
print(substring) -- Output: Hello
Example 2: Omitting the Ending Position
Extract a substring from the starting position to the end of the string.
Example 2
local substring = string.sub("Lua Programming", 5)
print(substring) -- Output: Programming
Example 3: Negative Indexing
Using negative indices to count from the end of the string.
Example 3
local substring = string.sub("Hello, World!", -6, -1)
print(substring) -- Output: World!
Example 4: Invalid Indices
Demonstrate behavior with invalid indices.
Example 4
local invalid = string.sub("Hello", 10)
print(invalid) -- Output: (empty string)
local empty = string.sub("Hello", 3, 2)
print(empty) -- Output: (empty string)
Use Cases
- String Manipulation: Extracting specific parts of strings for analysis or display.
- Data Processing: Useful in scenarios where only certain portions of a string are needed, such as parsing or formatting.
See also
string.len()
: Returns the length of a string, which can be helpful when determining valid indices forstring.sub()
.string.find()
: Can be used to locate substrings, which can then be extracted usingstring.sub()
.