Find the last offset in a string using Applescript

Alec Jacobson

July 29, 2009

weblog/

Applescript has famously awkward, clumsy and insufficient string operations. I set about trying to extract the base address of a url (or file path) with applescript (by the way ruby provides this with the method File.dirname). Applescript provides offset of as in the offset of "e" in "hello" is 2 (remember Applescript is 1-indexed). There is no easy equivalent to find the last occurrence in a string, the last offset. Here are my two solutions.
Solution One:
on last_offset(the_text, char)
	try
		set i to 1
		set last_occurrence to 0
		repeat count of the_text times
			if item i of the_text as string = char then
				set last_occurrence to i
			end if
			set i to i + 1
		end repeat
	on error
		return 0
	end try
	return last_occurrence
end last_offset
This is really Intro to Computer Programming 101 feeling. I return 0 if something goes wrong or there are no matches like the way offset of returns 0 for no match.
Solution Two:
on last_offset(the_text, char)
  try
    set len to count of the_text
    set reversed to reverse of characters of the_text as string
    set last_occurrence to len - (offset of char in reversed) + 1
    if last_occurrence > len then
      return 0
    end if
  on error
    return 0
  end try
  return last_occurrence
end last_offset

It doesn't seem like there's any reason why one of these is faster than the other.