Get last ASCII character of a string?

How does one find the last character of a string? I’m thinking this is a part of a larger script that is failing under 10.6 because of a deprecated method of finding the last character this_str; or it is failing due to the method of determining “ASCII character 32” being wrong:

if last character of this_str ends with (ASCII character 32) then
 "do stuff"

Thanks, Mark

This should work

set myString to "abcdef "

if (character -1 of myString) = (ASCII character 32) then
	display dialog "the string ends in a space"
	display dialog "not"
end if


since Leopard it’s recommended to use character id instead of ASCII character but there is a constant for a space character anyway.

The error in your script is last character . ends with, the correct syntax is either
last character . is or this_str . ends with

if this_str ends with space then
"do stuff"


As you may have gathered from mikerickson’s reply, you can use ‘if last character of this_str is .’ or ‘if this_str ends with .’. You don’t need a combination of the two. I believe the latter is slightly more efficient.

"ASCII character .’ and ‘ASCII number .’ are deprecated as from OS 10.5. They’ve been replace with ‘character id .’ and ‘id of .’.

character id 32 --> " "

id of " " --> 32

These are better able to deal with Unicode text and also work with more than one character at a time:

set this_str to "abcde "

id of this_str --> {97, 98, 99, 100, 101, 32}

character id {97, 98, 99, 100, 101, 32} --> "abcde "

For your purposes, of course, you don’t need to use either, since you can use the literal string " " or the AppleScript keyword ‘space’.

if this_str ends with " " then "do stuff"

if this_str ends with space then "do stuff"

Edit: Sorry, Stefan. You must have posted as I was composing this.

I just checked out the OP code and it works. (OS 10.5.8)

set this_str to "abc "

if last character of this_str ends with (ASCII character 32) then
	return "x"
end if

The only reason they should keep it is to have old scripts running…
Use the new term from now on. In Mac 10.7, ASCII character probably won’t work and old script won’t run.

maybe, but it’s grammatical nonsense :wink:

Not nessesarily, the string “x” does end with “x”

The only problem I see, and haven’t tested, is if there is a difference in the null (myString = “”) case.

I also wonder, since the OP script does work, if there is a different, hidden for the moment, issue that impelled the question to be asked.