Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Julia Strings

Julia Strings

A string is a finite sequence of zero or more characters. It is the data type used to represent text in programming languages.

Julia usually uses single quotes ' to create a single character, and double quotes " or triple double quotes """ to create strings:



c = 'x'                                   # Char 字符



str = "RUNOOB"                            # String 字符串



runoob = """Runoob Tutorial "RUNOOB",包含了引号"""   # 三引号字符串

Julia String Type Features:


Character

A single character is represented by a Char value, and character literals are enclosed in single quotes.

Char is a 32-bit primitive type that can be converted to its corresponding integer value, i.e. the Unicode code point:

Example

julia

c =

'x'

'x'

: ASCII/Unicode U+0078

(

category Ll: Letter,

lowercase

)

julia

typeof

(

c

)

Char

julia

c =

Int

(

'x'

)

   

Convert a character to an integer

120

julia

typeof

(

c

)

Int64

We can also convert an integer value back to Char:

Example

julia

Char

(

97

)

'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 on Char values:

Example

julia

'A'

<

'a'

true

julia

'A'

<

=

'X'

<

=

'Z'

true

julia

'x'

'a'

23

julia

'A'

1

'B'

: ASCII/Unicode U+0042

(

category Lu: Letter,

uppercase

)


String Basics

Strings in Julia can be declared with double quotes " or triple double quotes """. If you need double quotes inside the string, you can declare it with triple double quotes:

Example

julia

str =

"RUNOOB"

"RUNOOB"

julia

runoob =

"""Runoob Tutorial "RUNOOB", contains double quotes"""

"Runoob Tutorial "RUNOOB", contains double quotes"

If the string is too long, we can use a backslash \ to break it across lines:

Example

julia

"This is a long \
       line"

"This is a long line"

Index

Julia strings can be indexed like arrays to read the character at a given position; the starting index is 1 or begin, and the ending index is end:

Example

julia

str =

"RUNOOB"

"RUNOOB"

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 a substring:

Example

julia

str

[

begin:

end

]

"RUNOOB"

julia

str

[

begin:end-

1

]

"RUNOO"

julia

str

[

2

:

5

]

"UNOO"

In addition, the expressions str[k] and str[k:k] give different results: the former gets the character at a given position via indexing and has type Char; the latter reads the string over the given range, which is just a string that happens to contain one character:

Example

julia

str

[

6

]

'B'

: ASCII/Unicode U+0042

(

category Lu: Letter,

uppercase

)

julia

str

[

6

:

6

]

"B"

Range slicing can also be achieved using SubString the following method:

Example

julia

str =

"long string"

"long string"

julia

substr = SubString

(

str,

1

,

4

)

"long"

julia

typeof

(

substr

)

SubString

{

String

}

Multibyte Characters and Byte Indexing

Julia strings use UTF-8 encoding, and one Chinese character takes 3 bytes. String indices are actuallybyte indices, so not every numeric index is valid:

UTF-8 Byte Index Layout Diagram

Example

julia

s =

"RUNOOBTutorial"

julia

s

[

1

]

'R'

: ASCII/Unicode U+0052

(

category Lu: Letter,

uppercase

)

The 7th byte is the first byte of the Chinese character 'Jiao'; indices 5 and 6 land in the middle of the character and are invalid indices

julia

s

[

7

]

'Jiao' (a Chinese character)

: Unicode U+

6559

(

category Lo: Letter, other

)

julia

s

[

5

]

ERROR: StringIndexError: invalid

index

[

5

]

, valid nearby indices

[

4

]

=

'B'

,

[

7

]

=

'Jiao' (a Chinese character)

Stacktrace:

[

...

]

length counts characters, ncodeunits counts bytes

julia

length

(

s

)

8

julia

ncodeunits

(

s

)

12

nextind / prevind are used to move between valid indices

julia

nextind

(

s,

1

)

2

julia

collect

(

eachindex

(

s

)

)

   

All valid indices

8

-element

Vector

{

Int64

}

:

 

1

 

2

 

3

 

4

 

5

 

6

 

7

 

10

Note:When iterating a string, you can simply use for c in s to iterate by character, with no need to handle indices manually.


String concatenation

There are two common ways to concatenate strings. The first is the * operator, which is the idiomatic Julia way:

Example

julia

greet =

"Hello"

"Hello"

julia

whom =

"world"

"world"

Concatenate strings with the * operator

julia

greet

", "

whom

"!"

"Hello, world!"

Julia uses * instead of + to concatenate strings because string concatenation is not commutative ("ab" and "ba" are different), and in mathematics non-commutative operations are conventionally represented by a multiplication sign.

The second is the string() function, which can concatenate values of any type:

Example

julia

string

(

greet,

", "

, whom,

"."

,

123

)

"Hello, world.123"

The ^ operator can repeat a string (equivalent to the repeat function):

Example

julia

"RUNOOB "

^

3

"RUNOOB RUNOOB RUNOOB "

julia

repeat

(

"ab"

,

3

)

"ababab"


Interpolation

To reduce the tedium of concatenation, Julia allows interpolation of string literals with $, just like in Perl:

Example

julia

"$greet, $whom!"

"Hello, world!"

The shortest complete expression after $ is taken as the expression whose value is inserted into the string. Therefore, you can insert any expression into a string using parentheses:

Example

julia

"1 + 2 = $(1 + 2)"

"1 + 2 = 3"

The object is converted to its corresponding string representation

julia

v =

[

1

,

2

,

3

]

;

julia

"v: $v"

"v: [1, 2, 3]"

Char values are inserted without quotes

julia

c =

'x'

;

julia

"hi, $c"

"hi, x"

To include a literal $ in a string literal, escape it with a backslash:

Example

julia

print

(

"I have $100 in my account.\n"

)

I have $100

in

my account.


Triple-quoted string literals

Triple quotes """...""" provide a convenient way to create longer, more complex strings.

Triple-quoted strings have a special behavior:Automatic removal of indentation. It removes common leading whitespace based on the line with the least indentation (usually the line containing the closing """):

Example

julia

str =

"""
           Hello,
           world.
         """

"  Hello,\n  world.\n"

julia

println

(

str

)

  Hello,

  world.

If the opening """ is immediately followed by a newline, that newline is removed, which makes multi-line strings neater to write in code:

Example

julia

"""
         Hello,
         world."""

"Hello,\nworld."


Unicode and UTF-8

Julia fully supports Unicode characters and strings.

In character literals, Unicode code points can be represented with \u (up to 4 hex digits) and \U (up to 8 hex digits) escape sequences:

Example

julia

s =

"∀ x ∃ y"

"∀ x ∃ y"

String literals are encoded in UTF-8. UTF-8 is a variable-length encoding: ASCII characters (code points below 128) use a single byte, while characters with code point 0x80 and above use up to 4 bytes.


String Comparison and Searching

We can use comparison operators to compare strings in lexicographic order:

Example

julia

"abracadabra"

<

"xylophone"

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

julia

findfirst

(

'o'

,

"xylophone"

)

4

julia

findlast

(

'o'

,

"xylophone"

)

7

julia

findfirst

(

'z'

,

"xylophone"

)

   

Returns nothing when not found

You can pass a third argument and use the findnext and findprev functions to search for a character at a given offset:

Example

julia

findnext

(

'o'

,

"xylophone"

,

5

)

7

julia

findprev

(

'o'

,

"xylophone"

,

5

)

4

You can use the occursin function to check whether a substring can be found within a string:

Example

julia

occursin

(

"world"

,

"Hello, world."

)

true

julia

occursin

(

"RUNOOB"

,

"Hello, world."

)

false

julia

occursin

(

'o'

,

"Xylophon"

)

   

You can also search for a single character

true

Two commonly used conversion functions, repeat and join:

Example

julia

repeat

(

".:Z:."

,

3

)

".:Z:..:Z:..:Z:."

julia

join

(

[

"apples"

,

"bananas"

,

"pineapples"

]

,

", "

,

" and "

)

"apples, bananas and pineapples"

Other Common String Functions

function Description
firstindex(str) The smallest valid index for indexing (always 1 for strings)
lastindex(str) The largest valid index for indexing
length(str) Number of characters in str
ncodeunits(str) Number of code units (bytes) in the string
codeunit(str, i) Gives the code unit value at index i in string str
thisind(str, i) Given an arbitrary index, find the first index of the character it belongs to
nextind(str, i, n=1) Find the start of the n-th character after index i
prevind(str, i, n=1) Find the start of the n-th character before index i
startswith(s, prefix) Determine whether s starts with prefix
endswith(s, suffix) Determine whether s ends with suffix
strip(s) Remove leading and trailing whitespace
split(s, dlm) Split into an array of substrings by a delimiter
uppercase(s) / lowercase(s) Convert to uppercase / lowercase

Example

julia

startswith

(

"runoob.com"

,

"runoob"

)

true

julia

endswith

(

"runoob.com"

,

".com"

)

true

julia

strip

(

"  RUNOOB  "

)

"RUNOOB"

julia

split

(

"a,b,c"

,

","

)

3

-element

Vector

{

SubString

{

String

}

}

:

 

"a"

 

"b"

 

"c"

julia

uppercase

(

"runoob"

)

"RUNOOB"


Raw String Literals

Raw strings without interpolation or escaping can be written as non-standard string literals of the form raw"...", with content exactly as entered. This is useful for content such as regular expressions, LaTeX, Windows paths, and more:

Example

Ordinary strings interpret \n as a newline

julia

"runoob\nRUNOOB"

"runoob\nRUNOOB"

raw strings preserve the original

julia

raw

"runoob\nRUNOOB"

"runoob\nRUNOOB"

In raw strings, $ is not interpolated

julia

x =

1

;

julia

raw

"x = $x"

"x = $x"

The exception is that quotes must still be escaped; for example, raw""" is equivalent to """.


Byte Array and Version Number Literals

Julia also has two commonly used non-standard string literals:

b"..." Byte array literals, used to represent UInt8 arrays:

Example

julia

b

"RUNOOB"

6

-element Base.

CodeUnits

{

UInt8,

String

}

:

 0x52

 0x55

 0x4e

 0x4f

 0x4f

 0x42

v"..." Version number literals create VersionNumber objects, follow semantic versioning, and are often used for version comparison:

Example

julia

v

"1.10.4"

v

"1.10.4"

Compare version numbers

julia

v

"1.10"

<

v

"1.11"

true

julia

VERSION

= v

"1.6"

true