Core Function Sub
Sub( <expression>, <start>, <end>, <replacement> )
Contents |
Description
Return part of a string or replace it
Parameters
expression
The expression to evaluate.
start
The character position to start. (0 = first character)
OR
If the start is a negative value the character position will work backwards from the length of the string.
end
Optional; The character position to end.
If end is given and is negative, an end of -1 refers to the last character in a string, -2 to the previous one, and so on.
(Note - If you wish to extract a number of characters instead of from start to end position you should see SubStr())
replacement
Optional; If you set this parameter the substring will be replaced instead of returned so you will receive a new string with the substring replaced with the replacement text.
If you use the ->> you can force the original string to be modified see example below.
If the replacement and the part to be replaced are the same size it wont even need to reconstruct the string it can just edit it directly in ram.
Return Value
Success: Returns the extracted string.
Failure: Returns an empty string.
Remarks
Sub() works almost identical to SubStr() with only one change instead of taking the start position + length it takes a start position + end position this is useful for any functions that return start+end positions such as find() etc.
Example
Basic example
$var = Sub("I am a string", 2, 3); MsgBox("2 chars extracted from position 2 are: $var"); // am
Example using Start as a negative number
say Sub("UberFoX", -3); // Prints FoX say Sub("UberFoX", -4, -3); // Prints rF
More
my $s = "Hello Corona user"; say( sub($s, 6) );// -- Corona user say( sub($s, 6, 8) );// -- Cor say( sub($s, -11) );// -- Corona user say( sub($s, -11, 11) );// -- Corona say( sub($s, -11, -6) );// -- Corona
Using replacement and returning a new string
$str = "UberCat!"; print Sub($str, 4, 6, "FoX"); # Prints # UberFoX!
Using replacement and modifying the original string in place
# Normally when you do replacement on Sub it returns the string # with the changes made to it and leaves the original unchanged # but when you use ->> you can force the original to be changed # and have the replaced part returned instead example $str = "UberCat!"; print "String: $str\n"; $rep = $str->>Sub(4, 6, "FoX"); print "Replaced: $rep\n"; print "String: $str\n"; # String: UberCat! # Replaced: Cat # String: UberFoX!
Example of using an array as the second param
// Get a string my $s = "the quick brown fox"; // Find a word that ends in a number my List ( $Start, $End ) = find($s, "quick"); my $arr = array($Start, $End); say Sub($s, $arr); // Prints "quick" # Slghtly better than doing Sub($str, $arr[0], $arr[1]);
A pattern example
// Get a string my $s = "The quick12 dog"; // Find a word that ends in a number my List ( $Start, $End ) = find($s, "%a+(%d+)"); // Print it using its start+end position say Sub($s, $Start, $End); // Prints // quick12