Tuesday, September 27, 2022

#1 2022-09-09 05:41:49 am

KniazidisR
Member
From:: Greece
Registered: 2019-03-03
Posts: 2524

Replace Character of the Text at Index X

Using AsObjC-form handler:

Applescript:


on replaceCharacterOfText:aText atIndex:anIndex withCharacter:aChar
   set chars to characters of aText
   set item anIndex of chars to aChar
   return chars as text
end replaceCharacterOfText:atIndex:withCharacter:

my replaceCharacterOfText:"ebc" atIndex:2 withCharacter:"a"

.
.
The same using usual AppleScript handler with positional parameters:

Applescript:


on replaceCharacter(aText, anIndex, aChar)
   set chars to characters of aText
   set item anIndex of chars to aChar
   return chars as text
end replaceCharacter

replaceCharacter("ebc", 2, "a")

Last edited by KniazidisR (2022-09-09 05:45:55 am)


Model: MacBook Pro
OS X: Catalina 10.15.7
Web Browser: Safari 14.1
Ram: 4 GB

Offline

 

#2 2022-09-09 06:24:14 am

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 5563

Re: Replace Character of the Text at Index X

Hi KniazidisR.

How about some explicit setting of text item delimiters before coercing the list to text?  smile  Alternatively:

Applescript:


on replaceCharacterOfText:aText atIndex:anIndex withCharacter:aChar
   set ids to id of aText
   set item anIndex of ids to id of aChar
   return string id ids
end replaceCharacterOfText:atIndex:withCharacter:

my replaceCharacterOfText:"ebc" atIndex:2 withCharacter:"a"


NG

Offline

 

#3 2022-09-09 09:02:27 am

KniazidisR
Member
From:: Greece
Registered: 2019-03-03
Posts: 2524

Re: Replace Character of the Text at Index X

Nigel Garvey wrote:

Hi KniazidisR.

How about some explicit setting of text item delimiters before coercing the list to text?  smile  Alternatively:

Applescript:


on replaceCharacterOfText:aText atIndex:anIndex withCharacter:aChar
   set ids to id of aText
   set item anIndex of ids to id of aChar
   return string id ids
end replaceCharacterOfText:atIndex:withCharacter:

my replaceCharacterOfText:"ebc" atIndex:2 withCharacter:"a"



There is no "fool proof" in my code. This is bad.

I can of course explicitly set AppleScript's text item delimiters for this protection, but that would add 3 lines of code at once. And... I thought I had discovered America.

As I see it now, users are better off using the code suggested by you. It's short, quick, and independent of the current setting of AppleScript's text item delimiters.

Last edited by KniazidisR (2022-09-09 09:03:21 am)


Model: MacBook Pro
OS X: Catalina 10.15.7
Web Browser: Safari 14.1
Ram: 4 GB

Offline

 

#4 2022-09-09 01:28:06 pm

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 5563

Re: Replace Character of the Text at Index X

KniazidisR wrote:

And... I thought I had discovered America.


What a great expression!  ‘ lol


NG

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)