Set character x of string to character

I don’t know why this is stumping me, and I realize it’s probably a fairly simple answer, but my brain is being a bully and not telling me. :rolleyes:

How do I change a certain character in a string to another? ie:

set character 1 of "ebc" to "a"

As always, I thank you for your help!



if you want it quite flexible, some lines of code are required

property characterIndex : 3
property characterToReplace : "x"

set theString to "abcde"
set strCount to count theString

if characterIndex > strCount then
	return false
else if characterIndex = 1 then
	return characterToReplace & text 2 thru -1 of theString
else if characterIndex = strCount then
	return text 1 thru -2 of theString & characterToReplace
	return text 1 thru (characterIndex - 1) of theString & characterToReplace & text (characterIndex + 1) thru -1 of theString
end if


set aString to "abcde"
set chrChange to 4
set newChr to "X"

	set preString to text 1 thru chrChange of aString
	set preString to reverse of (rest of (reverse of characters of preString)) as string
	set postString to text chrChange thru -1 of aString
	set postString to rest of (characters of postString) as string
	return preString & newChr & postString -- "abcXe"
end try

return aString

As you’ve probably gathered from the replies, you can’t set a character of a string to anything ” not in vanilla AppleScript, anyway. You have to construct a new string containing the difference(s) you want. However, you often can directly change a character in the text of a document belonging to a scriptable application like TextEdit or Pages.

Don’t forget that list-to-string coercions are affected by the state of AppleScript’s text item delimiters, so these should be explicitly set to {“”} or “” beforehand to be absolutely sure the result’s what’s intended.

If you’re playing with lists, of course, you could simply get a list of the characters, change the relevant item in the list, and coerce the list back to text:

set aString to "abcde"
set chrChange to 4
set newChr to "X"

	set theCharacters to characters of aString
	set item chrChange of theCharacters to newChr
	set astid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to ""
	set aString to theCharacters as text
	set AppleScript's text item delimiters to astid
end try

return aString

Hm. Apple really should make this easier…

Thanks, guys! Big help! :smiley: