Literals/String: Difference between revisions
Content deleted Content added
No edit summary |
added J |
||
Line 136:
crlf = string([13b,10b])
=={{header|J}}==
Like C, J treats strings as lists of characters. Character literals are enclosed in single quotes, and there is no interpolation. Therefore, the only "escape" character neccessary is the single-quote itself, and within a character literal is represented by a pair of adjacent single quotes (much like in C, where within a character literal, a slash is represented by a pair of adjacent slashes).
Examples:
'x' NB. Scalar character
'string' NB. List of characters, i.e. a string
'can<nowiki>''</nowiki>t get simpler' NB. Embedded single-quote
Like VB, J can include newlines and other special characters in literals with concatentation. Also like VB, J comes with certain constants predefined for some characters:
'Here is line 1',LF,'and line two'
'On a mac, you need',CR,'a carriage return'
'And on windows, ',CRLF,'you need both'
TAB,TAB,TAB,'Everyone loves tabs!'
These constants are simply names assigned to selections from the ASCII alphabet. That is, the standard library executes lines like this:
CR =: 13 { a.
LF =: 10 { a.
CRLF =: CR,LF NB. Or just 10 13 { a.
TAB =: 9 { a.
Since these constants are nothing special, it can be seen that any variable can be similarly included in a literal:
NAME =: 'John Q. Public'
'Hello, ',NAME,' you may have already won $1,000,000'
For multiline literals, you may define an explicit noun, which is terminated by a lone <code>)</code> in the very first column:
template =: noun define
Hello, NAME.
My name is SHYSTER, and I'm here to tell
you that you my have already won $AMOUNT!!
To collect your winnings, please send $PAYMENT
to ADDRESS.
)
Simple substition is most easily effected by using loading a standard script:
load 'strings'
name =: 'John Q. Public'
shyster =: 'Ed McMahon'
amount =: 1e6
payment =: 2 * amount
address =: 'Publisher<nowiki>''</nowiki>s Clearing House'
targets =: ;: 'NAME SHYSTER AMOUNT PAYMENT ADDRESS'
sources =: ":&.> name;shyster;amount;payment;address
message =: template rplc targets,.sources
While C-like interpolation can be effected with another:
load 'printf'
'This should look %d%% familiar \nto programmers of %s.' sprintf 99;'C'
This should look 99% familiar
to programmers of C.
=={{header|Java}}==
|