String prepend: Difference between revisions

Added AppleScript.
No edit summary
(Added AppleScript.)
Line 196:
012345678
</pre>
 
=={{header|AppleScript}}==
 
AppleScript text is immutable, so prepending is only possible by creating a new text through concatenation of the variable's existing contents to the other string:
 
<lang applescript>set aVariable to "world!"
set aVariable to "Hello " & aVariable
return aVariable</lang>
 
{{output}}
<lang applescript>"Hello world!"</lang>
 
It's a similar situation with NSString class in AppleScriptObjC. This has various ways of achieving the same thing, probably the most sensible of which is the first of the following:
 
<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
set aVariable to current application's class "NSString"'s stringWithString:("world!")
set aVariable to aVariable's stringByReplacingCharactersInRange:({0, 0}) withString:("Hello ")
-- return aVariable as text
 
-- Or:
set aVariable to current application's class "NSString"'s stringWithString:("world!")
set aVariable to current application's class "NSString"'s stringWithFormat_("%@%@", "Hello ", aVariable)
-- return aVariable as text
 
-- Or:
set aVariable to current application's class "NSString"'s stringWithString:("world!")
set aVariable to aVariable's stringByReplacingOccurrencesOfString:("^") withString:("Hello ") ¬
options:(current application's NSRegularExpressionSearch) range:({0, 0})
-- return aVariable as text</lang>
 
But there's also an NS''Mutable''String class. This has 'replace' versions of the 'stringByReplacing' methods above and also this <tt>insertString:atIndex:</tt> method:
 
<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
set aVariable to current application's class "NSMutableString"'s stringWithString:("world!")
tell aVariable to insertString:("Hello ") atIndex:(0)
return aVariable as text</lang>
 
{{output}}
<lang applescript>"Hello world!"</lang>
 
=={{header|AutoHotkey}}==
557

edits