Julia Strings
A string is a finite sequence of zero or more characters. It is a data type in programming languages used to represent text.
Julia typically uses single quotes'to create individual characters, and double quotes"or three quotes"""to create strings. For example:
c = 'x' str = "EXAMPLE" example = """Example "EXAMPLE",包含了单个引号"""
Julia string type characteristics:
- The built-in concrete type used for strings (and string literals) in Julia is String.
- Julia's string types are all subtypes of the abstract type AbstractString.
- Julia has an excellent type for representing single characters, namely AbstractChar. Char is a built-in subtype of AbstractChar, a 32-bit primitive type that can represent any Unicode character (based on UTF-8 encoding).
- Julia strings are immutable — the value of any AbstractString object cannot be changed.
Characters
Individual characters are represented by Char values.
Char is a 32-bit primitive type that can be converted to its corresponding integer value, i.e., the Unicode code:
Example
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
julia> typeof(c)
Char
julia> c = Int('x')
120
julia> typeof(c)
Int64
We can also convert an integer value to a Char:
Example
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> Char(120)
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
We can perform comparisons and limited arithmetic operations on Char values:
Example
true
julia> 'A' <= 'a' <= 'Z'
false
julia> 'A' <= 'X' <= 'Z'
true
julia> 'x' - 'a'
23
julia> 'A' + 1
'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
Strings
Strings in Julia can be declared using double quotes"or three double quotes"""If you need to use quotes in a part of a string, you can use three double quotes to do so, as shown below:
Example
"EXAMPLE"
julia> example = """Example tutorial "EXAMPLE", contains a single quote"""
“Rookie Tutorial\"EXAMPLE\", contains a single quote"
If the string is too long, we can use a backslash\to split it:
Example
line"
"This is a long line"
Example
"EXAMPLE"
julia> str[begin]
'R': ASCII/Unicode U+0052 (category Lu: Letter, uppercase)
julia> str[1]
'R': ASCII/Unicode U+0052 (category Lu: Letter, uppercase)
julia> str[2]
'U': ASCII/Unicode U+0055 (category Lu: Letter, uppercase)
julia> str[end]
'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
julia> str[end-1]
'O': ASCII/Unicode U+004F (category Lu: Letter, uppercase)
We can use range indexing to extract substrings:
Example
"EXAMPLE"
julia> str[begin:end]
"EXAMPLE"
julia> str[begin:end-1]
"RUNOO"
julia> str[2:5]
"UNOO"
In addition, the expressionsstr[k]andstr[k:k]give different results: the former obtains the character at a specified position via indexing, and its type is Char; the latter reads the string via the given range, except that it is just a string containing one character:
Example
'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
julia> str[6:6]
"B"
Range extraction can also be implemented using theSubStringmethod, for example:
Example
"long string"
julia> substr = SubString(str, 1, 4)
"long"
julia> typeof(substr)
SubString{String}
String Concatenation
We can use the string() method to concatenate multiple strings:Example
"Hello"
julia> whom = "world"
"world"
julia> string(greet, ", ", whom, ".\n")
"Hello, world.\n"
Interpolation
The way of constructing strings by concatenation is sometimes a bit cumbersome. To reduce redundant calls to string or repeated multiplication, Julia allows interpolation of string literals using $, as in Perl:
Example
"Hello, world.\n"
This is more readable and convenient, and is equivalent to the string concatenation above — the system rewrites this apparently one-line string literal into a concatenation of string literals with arguments.string(greet, ", ", whom, ".\n")。
In$The shortest complete expression after the `$` is taken as the expression whose value is inserted into the string. Therefore, you can insert any expression into a string using parentheses:
Example
"1 + 2 = 3"
Both concatenation and interpolation call string to convert objects to string form. However, string actually simply returns the output of print, so new types should add print or show methods rather than a string method.
Most non-AbstractString objects are converted to strings that closely correspond to the way they are entered as text expressions:
Example
3-element Vector{Int64}:
1
2
3
julia> "v: $v"
"v: [1, 2, 3]"
string is the identity for AbstractString and AbstractChar values, so they are inserted into strings as themselves, without quoting or escaping:
Example
'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
julia> "hi, $c"
"hi, x"
If you want to include the literal `$` in a string literal$, escape it with a backslash:
Example
I have $100 in my account.
Unicode and UTF-8
Julia fully supports Unicode characters and strings.
In character literals, Unicode code points can be represented using the Unicode \u and \U escape sequences, as well as all standard C escape sequences. These can also be used to write string literals:
Example
"∀ x ∃ y"
Whether these Unicode characters are displayed as escapes or as special characters depends on your terminal's locale settings and its support for Unicode. String literals are encoded in UTF-8. UTF-8 is a variable-length encoding, meaning that not all characters are encoded with the same number of bytes (code units). In UTF-8, ASCII characters (those less than 0x80 (128)) are encoded with a single byte, just as they are in ASCII; characters at 0x80 and above are encoded with up to 4 bytes.
Triple-Quoted String Literals
Triple quotes"""..."""provide convenience for creating longer and more complex strings. Inside triple quotes, newlines, quotes, and indentation can be used conveniently without special handling.
Example
Hello,
world.
"""
" Hello,\n world.\n"
String Comparison
We can use comparison operators to compare strings in lexicographic order:
Example
true
julia> "abracadabra" == "xylophone"
false
julia> "Hello, world." != "Goodbye, world."
true
julia> "1 + 2 = 3" == "1 + 2 = $(1 + 2)"
true
You can use the findfirst and findlast functions to search for the index of a specific character:
Example
4
julia> findlast(isequal('o'), "xylophone")
7
julia> findfirst(isequal('z'), "xylophone")
You can pass a third argument and use the findnext and findprev functions to search for a character at a given offset:
Example
4
julia> findnext(isequal('o'), "xylophone", 5)
7
julia> findprev(isequal('o'), "xylophone", 5)
4
julia> findnext(isequal('o'), "xylophone", 8)
You can use the occursin function to check whether a substring can be found in a string.
Example
true
julia> occursin("o", "Xylophon")
true
julia> occursin("a", "Xylophon")
false
julia> occursin('o', "Xylophon")
true
The last example shows that occursin can also be used to search for character literals.
There are also two convenient string functions, repeat and join:
Example
".:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:."
julia> join(["apples", "bananas", "pineapples"], ", ", " and ")
"apples, bananas and pineapples"
Other useful functions include:
- firstindex(str)- Returns the minimum (byte) index that can be used to index into str (for strings this is always 1, but not necessarily for other containers).
- lastindex(str)- Returns the maximum (byte) index that can be used to index into str.
- length(str)- The number of characters in str.
- length(str, i, j)- The number of valid character indices from i to j in str.
- ncodeunits(str)- The number of code units in the string.
- codeunit(str, i)- Returns the value of the code unit at index i in the string str.
- thisind(str, i)- Given an arbitrary index into a string, finds the first index of the character containing that index.
- nextind(str, i, n=1)- Finds the start of the n-th character after index i.
- prevind(str, i, n=1)- Finds the start of the n-th character before index i.
Raw String Literals
Raw strings without interpolation and unescaping can be represented byraw"..."non-standard string literals. Raw string literals produce ordinary String objects that contain the enclosed content exactly as input, without interpolation and unescaping. This is useful for strings containing code or markup in other languages that use"or\"\ as a special character.
The exception is that quotes must still be escaped, for exampleraw"\""is equivalent to"\"". In order to be able to express all strings, backslashes must also be escaped, but only when they appear immediately before a quote.
julia> println(raw"\\ \\\"") \\ \"
Note that the first two backslashes appear verbatim in the output because they are not before a quote. However, the next backslash character escapes the following backslash; and since these backslashes appear before a quote, the last backslash escapes a quote.
Other Extensions