Friday, October 24, 2014

#1 2006-03-23 05:00:00 pm

julifos
Administrator
From: MalasaƱa, Madrid
Registered: 2002-11-20
Posts: 2014

Substring: "text" against "characters"

Does it really matter if I use 'text' or 'characters' when extracting parts from a given text?

We sometimes see code that might go something like this:

Applescript:

set someText to "Now is the time for all men to come to..."

text 12 thru 23 of someText --> "time for all"

It's often assumed that this is pretty much the same as saying:

Applescript:

set someText to "Now is the time for all men to come to..."

characters 12 thru 23 of someText as text --> "time for all"

However, while the results might appear to be the same in both cases, the operations involved are quite different. When using 'text', the relevant text is extracted intact - with no extra coercions involved. By contrast, 'characters':

-Produces a list of the text's characters in the first place:

Applescript:

"Now is the time for all men to come to..."

characters 12 thru 23 of result --> {"t", "i", "m", "e", " ", "f", "o", "r", " ", "a", "l", "l"}

-Coerces this list back to text:

Applescript:

result as text --> "time for all"

And we could have various side-effects when using 'characters' against 'text':
-Longer speed execution (as we have various operations).
-Unexpected results depending on the state of AppleScript's text item delimiters. Eg:

Applescript:

set text item delimiters to "_"
set someText to "Now is the time for all men to come to..."

text 12 thru 23 of someText --> "time for all"
characters 12 thru 23 of someText as text --> "t_i_m_e_ _f_o_r_ _a_l_l"

-Data type alteration. Eg:

Applescript:

set someText to "{Hello world}" as Unicode text

class of (text 2 thru -2 of someText) --> Unicode text
class of (characters 2 thru -2 of someText as text) --> string

--> credits to Kai Edwards for this FAQ.

Offline

 

Board footer

Powered by FluxBB

[ Generated in 0.032 seconds, 10 queries executed ]

RSS (new topics) RSS (active topics)