I’m looking for the simplest way of getting the offset of the last occurrance of a character in a string.
Is the an easy way?
Regards
Santa
set textstring to "hours" & return & "test *********" & return & "Variable string ********************" & return & "Have a good day."
set L to offset of "*" from end of textstring -- Doesn't work
display dialog L
--set temp to text (((offset of "hours" in textstring)+5) thru L) in textstring
set thischar to "*"
set textstring to "hours" & return & "test *********" & return & "Variable string ********************" & return & "Have a good day."
return (length of textstring) - (offset of thischar in (reverse of text items of textstring as string))
-- 56
Note that this list to string coercion is dependent on the current text item delimiters; It would be best to set them to an explicit value.
Try something like this:
on reverse_offset(needle, haystack)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to ""
set haystack to "" & reverse of text items of haystack
set text item delimiters of AppleScript to prevTIDs
set theOffset to offset of needle in haystack
if result is not 0 then
set theOffset to (count (haystack)) - theOffset + 1
end if
return theOffset
end reverse_offset
reverse_offset("*", "*example*")
--> 9
Note that this handler better replicates the expected results of the offset command: The first character of a string should return 1, and 0 should be returned when the needle is not found.
reverse_offset("*", "*example*")
on reverse_offset(d, t)
if t contains d then
set AppleScript's text item delimiters to d
set l to text items of t
set AppleScript's text item delimiters to ""
return (count of t) - (count of item -1 of l)
else
return 0
end if
end reverse_offset
Yvan KOENIG (from FRANCE dimanche 8 mars 2009 22:35:48)
reverse_offset("*", "*example*")
on reverse_offset(d, t)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to d
set ro to (count t) - (count text item -1 of t)
set AppleScript's text item delimiters to astid
return ro
end reverse_offset