Tech Tip: Utility method to return character at string position
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: May 1, 2023
The method below takes a string and position (integer) value and returns the character located at the specified position in the string. This method supports positive and negative integer values. If positive, the position is counted from the first character starting at index 0. If negative, the position is counted backwards from last string character starting at index -1. If string is empty, “” is returned.
/* METHOD: stringAt * INPUT: (1) target string * (2) position (index) of string character * OUTPUT: string character at position * NOTE: If position is positive, counts forward from (0) first character. * If position is negative, counts backward from (-1) last character. * Returns "" if empty string input. */ #DECLARE($str : Text; $idx : Integer)->$char : Text If (Count parameters=2) If ($str="") $char:="" Else If (($idx>=0) & ($idx<Length($str))) $char:=$str[[$idx+1]] Else If (($idx>=(-1*Length($str))) & ($idx<0)) $char:=$str[[Length($str)+$idx+1]] Else ALERT("Position is out of range.") End if End if End if Else ALERT("Incorrect amount of parameters.") End if |
Example 1:
$str:="us.4d.com" $idx:=6 $char:=stringAt($str; $idx) // "c" |
Example 2:
$str:="blog.4d.com" $idx:=-5 $char:=stringAt($str; $idx) // "d" |