字符串

Core.AbstractChar — Type

The AbstractChar type is the supertype of all character implementations in Julia. A character represents a Unicode code point, and can be converted to an integer via the codepoint function in order to obtain the numerical value of the code point, or constructed from the same integer. These numerical values determine how characters are compared with < and ==, for example. New T <: AbstractChar types should define a codepoint(::T) method and a T(::UInt32) constructor, at minimum.

A given AbstractChar subtype may be capable of representing only a subset of Unicode, in which case conversion from an unsupported UInt32 value may throw an error. Conversely, the built-in Char type represents a superset of Unicode (in order to losslessly encode invalid byte streams), in which case conversion of a non-Unicode value to UInt32 throws an error. The isvalid function can be used to check which codepoints are representable in a given AbstractChar type.

Internally, an AbstractChar type may use a variety of encodings. Conversion via codepoint(char) will not reveal this encoding because it always returns the Unicode value of the character. print(io, c) of any c::AbstractChar produces an encoding determined by io (UTF-8 for all built-in IO types), via conversion to Char if necessary.

write(io, c), in contrast, may emit an encoding depending on typeof(c), and read(io, typeof(c)) should read the same encoding as write. New AbstractChar types must provide their own implementations of write and read.

source

Core.Char — Type

1. Char(c::Union{Number,AbstractChar})

Char is a 32-bit AbstractChar type that is the default representation of characters in Julia. Char is the type used for character literals like 'x' and it is also the element type of String.

In order to losslessly represent arbitrary byte streams stored in a String, a Char value may store information that cannot be converted to a Unicode codepoint — converting such a Char to UInt32 will throw an error. The isvalid(c::Char) function can be used to query whether c represents a valid Unicode character.

source

Base.codepoint — Function

1. codepoint(c::AbstractChar) -> Integer

Return the Unicode codepoint (an unsigned integer) corresponding to the character c (or throw an exception if c does not represent a valid character). For Char, this is a UInt32 value, but AbstractChar types that represent only a subset of Unicode may return a different-sized integer (e.g. UInt8).

source

Base.length — Method

1. length(s::AbstractString) -> Int
2. length(s::AbstractString, i::Integer, j::Integer) -> Int

Return the number of characters in string s from indices i through j.

This is computed as the number of code unit indices from i to j which are valid character indices. With only a single string argument, this computes the number of characters in the entire string. With i and j arguments it computes the number of indices between i and j inclusive that are valid indices in the string s. In addition to in-bounds values, i may take the out-of-bounds value ncodeunits(s) + 1 and j may take the out-of-bounds value 0.

Note

The time complexity of this operation is linear in general. That is, it will take the time proportional to the number of bytes or characters in the string because it counts the value on the fly. This is in contrast to the method for arrays, which is a constant-time operation.

See also isvalid, ncodeunits, lastindex, thisind, nextind, prevind.

Examples

1. julia> length("jμΛIα")
2. 5

source

Base.sizeof — Method

1. sizeof(str::AbstractString)

Size, in bytes, of the string str. Equal to the number of code units in str multiplied by the size, in bytes, of one code unit in str.

Examples

1. julia> sizeof("")
2. 0

4. julia> sizeof("∀")
5. 3

source

Base.:* — Method

1. *(s::Union{AbstractString, AbstractChar}, t::Union{AbstractString, AbstractChar}...) -> AbstractString

Concatenate strings and/or characters, producing a String. This is equivalent to calling the string function on the arguments. Concatenation of built-in string types always produces a value of type String but other string types may choose to return a string of a different type as appropriate.

Examples

1. julia> "Hello " * "world"
2. "Hello world"

4. julia> 'j' * "ulia"
5. "julia"

source

Base.:^ — Method

1. ^(s::Union{AbstractString,AbstractChar}, n::Integer)

Repeat a string or character n times. This can also be written as repeat(s, n).

See also repeat.

Examples

1. julia> "Test "^3
2. "Test Test Test "

source

Base.string — Function

1. string(n::Integer; base::Integer = 10, pad::Integer = 1)

Convert an integer n to a string in the given base, optionally specifying a number of digits to pad to.

See also digits, bitstring, count_zeros.

Examples

1. julia> string(5, base = 13, pad = 4)
2. "0005"

4. julia> string(-13, base = 5, pad = 4)
5. "-0023"

source

1. string(xs...)

Create a string from any values using the print function.

string should usually not be defined directly. Instead, define a method print(io::IO, x::MyType). If string(x) for a certain type needs to be highly efficient, then it may make sense to add a method to string and define print(io::IO, x::MyType) = print(io, string(x)) to ensure the functions are consistent.

See also: String, repr, sprint, show.

Examples

1. julia> string("a", 1, true)
2. "a1true"

source

Base.repeat — Method

1. repeat(s::AbstractString, r::Integer)

Repeat a string r times. This can be written as s^r.

See also ^.

Examples

1. julia> repeat("ha", 3)
2. "hahaha"

source

Base.repeat — Method

1. repeat(c::AbstractChar, r::Integer) -> String

Repeat a character r times. This can equivalently be accomplished by calling c^r.

Examples

1. julia> repeat('A', 3)
2. "AAA"

source

Base.repr — Method

1. repr(x; context=nothing)

Create a string from any value using the show function. You should not add methods to repr; define a show method instead.

The optional keyword argument context can be set to a :key=>value pair, a tuple of :key=>value pairs, or an IO or IOContext object whose attributes are used for the I/O stream passed to show.

Note that repr(x) is usually similar to how the value of x would be entered in Julia. See also repr(MIME(“text/plain”), x) to instead return a “pretty-printed” version of x designed more for human consumption, equivalent to the REPL display of x.

Julia 1.7

Passing a tuple to keyword context requires Julia 1.7 or later.

Examples

1. julia> repr(1)
2. "1"

4. julia> repr(zeros(3))
5. "[0.0, 0.0, 0.0]"

7. julia> repr(big(1/3))
8. "0.333333333333333314829616256247390992939472198486328125"

10. julia> repr(big(1/3), context=:compact => true)
11. "0.333333"

source

Core.String — Method

1. String(s::AbstractString)

Convert a string to a contiguous byte array representation encoded as UTF-8 bytes. This representation is often appropriate for passing strings to C.

source

Base.SubString — Type

1. SubString(s::AbstractString, i::Integer, j::Integer=lastindex(s))
2. SubString(s::AbstractString, r::UnitRange{<:Integer})

Like getindex, but returns a view into the parent string s within range i:j or r respectively instead of making a copy.

Examples

1. julia> SubString("abc", 1, 2)
2. "ab"

4. julia> SubString("abc", 1:2)
5. "ab"

7. julia> SubString("abc", 2)
8. "bc"

source

Base.transcode — Function

1. transcode(T, src)

Convert string data between Unicode encodings. src is either a String or a Vector{UIntXX} of UTF-XX code units, where XX is 8, 16, or 32. T indicates the encoding of the return value: String to return a (UTF-8 encoded) String or UIntXX to return a Vector{UIntXX} of UTF-XX data. (The alias Cwchar_t can also be used as the integer type, for converting wchar_t* strings used by external C libraries.)

The transcode function succeeds as long as the input data can be reasonably represented in the target encoding; it always succeeds for conversions between UTF-XX encodings, even for invalid Unicode data.

Only conversion to/from UTF-8 is currently supported.

source

Base.unsafe_string — Function

1. unsafe_string(p::Ptr{UInt8}, [length::Integer])

Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8. (The pointer can be safely freed afterwards.) If length is specified (the length of the data in bytes), the string does not have to be NUL-terminated.

This function is labeled “unsafe” because it will crash if p is not a valid memory address to data of the requested length.

source

Base.ncodeunits — Method

1. ncodeunits(s::AbstractString) -> Int

Return the number of code units in a string. Indices that are in bounds to access this string must satisfy 1 ≤ i ≤ ncodeunits(s). Not all such indices are valid – they may not be the start of a character, but they will return a code unit value when calling codeunit(s,i).

Examples

1. julia> ncodeunits("The Julia Language")
2. 18

4. julia> ncodeunits("∫eˣ")
5. 6

7. julia> ncodeunits('∫'), ncodeunits('e'), ncodeunits('ˣ')
8. (3, 1, 2)

See also codeunit, checkbounds, sizeof, length, lastindex.

source

Base.codeunit — Function

1. codeunit(s::AbstractString) -> Type{<:Union{UInt8, UInt16, UInt32}}

Return the code unit type of the given string object. For ASCII, Latin-1, or UTF-8 encoded strings, this would be UInt8; for UCS-2 and UTF-16 it would be UInt16; for UTF-32 it would be UInt32. The code unit type need not be limited to these three types, but it’s hard to think of widely used string encodings that don’t use one of these units. codeunit(s) is the same as typeof(codeunit(s,1)) when s is a non-empty string.

See also ncodeunits.

source

1. codeunit(s::AbstractString, i::Integer) -> Union{UInt8, UInt16, UInt32}

Return the code unit value in the string s at index i. Note that

1. codeunit(s, i) :: codeunit(s)

I.e. the value returned by codeunit(s, i) is of the type returned by codeunit(s).

Examples

1. julia> a = codeunit("Hello", 2)
2. 0x65

4. julia> typeof(a)
5. UInt8

See also ncodeunits, checkbounds.

source

Base.codeunits — Function

1. codeunits(s::AbstractString)

Obtain a vector-like object containing the code units of a string. Returns a CodeUnits wrapper by default, but codeunits may optionally be defined for new string types if necessary.

Examples

1. julia> codeunits("Juλia")
2. 6-element Base.CodeUnits{UInt8, String}:
3. 0x4a
4. 0x75
5. 0xce
6. 0xbb
7. 0x69
8. 0x61

source

Base.ascii — Function

1. ascii(s::AbstractString)

Convert a string to String type and check that it contains only ASCII data, otherwise throwing an ArgumentError indicating the position of the first non-ASCII byte.

Examples

1. julia> ascii("abcdeγfgh")
2. ERROR: ArgumentError: invalid ASCII at index 6 in "abcdeγfgh"
3. Stacktrace:
4. [...]

6. julia> ascii("abcdefgh")
7. "abcdefgh"

source

Base.Regex — Type

1. Regex(pattern[, flags])

A type representing a regular expression. Regex objects can be used to match strings with match.

Regex objects can be created using the @r_str string macro. The Regex(pattern[, flags]) constructor is usually used if the pattern string needs to be interpolated. See the documentation of the string macro for details on flags.

Note

To escape interpolated variables use \Q and \E (e.g. Regex("\\Q$x\\E"))

source

Base.@r_str — Macro

1. @r_str -> Regex

Construct a regex, such as r"^[a-z]*$", without interpolation and unescaping (except for quotation mark " which still has to be escaped). The regex also accepts one or more flags, listed after the ending quote, to change its behaviour:

  • i enables case-insensitive matching
  • m treats the ^ and $ tokens as matching the start and end of individual lines, as opposed to the whole string.
  • s allows the . modifier to match newlines.
  • x enables “comment mode”: whitespace is enabled except when escaped with \, and # is treated as starting a comment.
  • a disables UCP mode (enables ASCII mode). By default \B, \b, \D, \d, \S, \s, \W, \w, etc. match based on Unicode character properties. With this option, these sequences only match ASCII characters.

See Regex if interpolation is needed.

Examples

1. julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
2. RegexMatch("angry,\nBad world")

This regex has the first three flags enabled.

source

Base.SubstitutionString — Type

1. SubstitutionString(substr)

Stores the given string substr as a SubstitutionString, for use in regular expression substitutions. Most commonly constructed using the @s_str macro.

1. julia> SubstitutionString("Hello \\g<name>, it's \\1")
2. s"Hello \g<name>, it's \1"

4. julia> subst = s"Hello \g<name>, it's \1"
5. s"Hello \g<name>, it's \1"

7. julia> typeof(subst)
8. SubstitutionString{String}

source

Base.@s_str — Macro

1. @s_str -> SubstitutionString

Construct a substitution string, used for regular expression substitutions. Within the string, sequences of the form \N refer to the Nth capture group in the regex, and \g<groupname> refers to a named capture group with name groupname.

1. julia> msg = "#Hello# from Julia";

3. julia> replace(msg, r"#(.+)# from (?<from>\w+)" => s"FROM: \g<from>; MESSAGE: \1")
4. "FROM: Julia; MESSAGE: Hello"

source

Base.@raw_str — Macro

1. @raw_str -> String

Create a raw string without interpolation and unescaping. The exception is that quotation marks still must be escaped. Backslashes escape both quotation marks and other backslashes, but only when a sequence of backslashes precedes a quote character. Thus, 2n backslashes followed by a quote encodes n backslashes and the end of the literal while 2n+1 backslashes followed by a quote encodes n backslashes followed by a quote character.

Examples

1. julia> println(raw"\ $x")
2. \ $x

4. julia> println(raw"\"")
5. "

7. julia> println(raw"\\\"")
8. \"

10. julia> println(raw"\\x \\\"")
11. \\x \"

source

Base.@b_str — Macro

1. @b_str

Create an immutable byte (UInt8) vector using string syntax.

Examples

1. julia> v = b"12\x01\x02"
2. 4-element Base.CodeUnits{UInt8, String}:
3. 0x31
4. 0x32
5. 0x01
6. 0x02

8. julia> v[2]
9. 0x32

source

Base.Docs.@html_str — Macro

1. @html_str -> Docs.HTML

Create an HTML object from a literal string.

Examples

1. julia> html"Julia"
2. HTML{String}("Julia")

source

Base.Docs.@text_str — Macro

1. @text_str -> Docs.Text

Create a Text object from a literal string.

Examples

1. julia> text"Julia"
2. Julia

source

Base.isvalid — Method

1. isvalid(value) -> Bool

Returns true if the given value is valid for its type, which currently can be either AbstractChar or String or SubString{String}.

Examples

1. julia> isvalid(Char(0xd800))
2. false

4. julia> isvalid(SubString(String(UInt8[0xfe,0x80,0x80,0x80,0x80,0x80]),1,2))
5. false

7. julia> isvalid(Char(0xd799))
8. true

source

Base.isvalid — Method

1. isvalid(T, value) -> Bool

Returns true if the given value is valid for that type. Types currently can be either AbstractChar or String. Values for AbstractChar can be of type AbstractChar or UInt32. Values for String can be of that type, SubString{String}, Vector{UInt8}, or a contiguous subarray thereof.

Examples

1. julia> isvalid(Char, 0xd800)
2. false

4. julia> isvalid(String, SubString("thisisvalid",1,5))
5. true

7. julia> isvalid(Char, 0xd799)
8. true

Julia 1.6

Support for subarray values was added in Julia 1.6.

source

Base.isvalid — Method

1. isvalid(s::AbstractString, i::Integer) -> Bool

Predicate indicating whether the given index is the start of the encoding of a character in s or not. If isvalid(s, i) is true then s[i] will return the character whose encoding starts at that index, if it’s false, then s[i] will raise an invalid index error or a bounds error depending on if i is in bounds. In order for isvalid(s, i) to be an O(1) function, the encoding of s must be self-synchronizing. This is a basic assumption of Julia’s generic string support.

See also getindex, iterate, thisind, nextind, prevind, length.

Examples

1. julia> str = "αβγdef";

3. julia> isvalid(str, 1)
4. true

6. julia> str[1]
7. 'α': Unicode U+03B1 (category Ll: Letter, lowercase)

9. julia> isvalid(str, 2)
10. false

12. julia> str[2]
13. ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'α', [3]=>'β'
14. Stacktrace:
15. [...]

source

Base.match — Function

1. match(r::Regex, s::AbstractString[, idx::Integer[, addopts]])

Search for the first match of the regular expression r in s and return a RegexMatch object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing m.match and the captured sequences can be retrieved by accessing m.captures The optional idx argument specifies an index at which to start the search.

Examples

1. julia> rx = r"a(.)a"
2. r"a(.)a"

4. julia> m = match(rx, "cabac")
5. RegexMatch("aba", 1="b")

7. julia> m.captures
8. 1-element Vector{Union{Nothing, SubString{String}}}:
9. "b"

11. julia> m.match
12. "aba"

14. julia> match(rx, "cabac", 3) === nothing
15. true

source

Base.eachmatch — Function

1. eachmatch(r::Regex, s::AbstractString; overlap::Bool=false)

Search for all matches of the regular expression r in s and return an iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.

Examples

1. julia> rx = r"a.a"
2. r"a.a"

4. julia> m = eachmatch(rx, "a1a2a3a")
5. Base.RegexMatchIterator(r"a.a", "a1a2a3a", false)

7. julia> collect(m)
8. 2-element Vector{RegexMatch}:
9. RegexMatch("a1a")
10. RegexMatch("a3a")

12. julia> collect(eachmatch(rx, "a1a2a3a", overlap = true))
13. 3-element Vector{RegexMatch}:
14. RegexMatch("a1a")
15. RegexMatch("a2a")
16. RegexMatch("a3a")

source

Base.RegexMatch — Type

1. RegexMatch

A type representing a single match to a Regex found in a string. Typically created from the match function.

The match field stores the substring of the entire matched string. The captures field stores the substrings for each capture group, indexed by number. To index by capture group name, the entire match object should be indexed instead, as shown in the examples. The location of the start of the match is stored in the offset field. The offsets field stores the locations of the start of each capture group, with 0 denoting a group that was not captured.

This type can be used as an iterator over the capture groups of the Regex, yielding the substrings captured in each group. Because of this, the captures of a match can be destructured. If a group was not captured, nothing will be yielded instead of a substring.

Methods that accept a RegexMatch object are defined for iterate, length, eltype, keys, haskey, and getindex, where keys are the the names or numbers of a capture group. See keys for more information.

Examples

1. julia> m = match(r"(?<hour>\d+):(?<minute>\d+)(am|pm)?", "11:30 in the morning")
2. RegexMatch("11:30", hour="11", minute="30", 3=nothing)

4. julia> hr, min, ampm = m;

6. julia> hr
7. "11"

9. julia> m["minute"]
10. "30"

12. julia> m.match
13. "11:30"

source

Base.keys — Method

1. keys(m::RegexMatch) -> Vector

Return a vector of keys for all capture groups of the underlying regex. A key is included even if the capture group fails to match. That is, idx will be in the return value even if m[idx] == nothing.

Unnamed capture groups will have integer keys corresponding to their index. Named capture groups will have string keys.

Julia 1.6

This method was added in Julia 1.6

Examples

1. julia> keys(match(r"(?<hour>\d+):(?<minute>\d+)(am|pm)?", "11:30"))
2. 3-element Vector{Any}:
3. "hour"
4. "minute"
5. 3

source

Base.isless — Method

1. isless(a::AbstractString, b::AbstractString) -> Bool

Test whether string a comes before string b in alphabetical order (technically, in lexicographical order by Unicode code points).

Examples

1. julia> isless("a", "b")
2. true

4. julia> isless("β", "α")
5. false

7. julia> isless("a", "a")
8. false

source

Base.:== — Method

1. ==(a::AbstractString, b::AbstractString) -> Bool

Test whether two strings are equal character by character (technically, Unicode code point by code point).

Examples

1. julia> "abc" == "abc"
2. true

4. julia> "abc" == "αβγ"
5. false

source

Base.cmp — Method

1. cmp(a::AbstractString, b::AbstractString) -> Int

Compare two strings. Return 0 if both strings have the same length and the character at each index is the same in both strings. Return -1 if a is a prefix of b, or if a comes before b in alphabetical order. Return 1 if b is a prefix of a, or if b comes before a in alphabetical order (technically, lexicographical order by Unicode code points).

Examples

1. julia> cmp("abc", "abc")
2. 0

4. julia> cmp("ab", "abc")
5. -1

7. julia> cmp("abc", "ab")
8. 1

10. julia> cmp("ab", "ac")
11. -1

13. julia> cmp("ac", "ab")
14. 1

16. julia> cmp("α", "a")
17. 1

19. julia> cmp("b", "β")
20. -1

source

Base.lpad — Function

1. lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String

Stringify s and pad the resulting string on the left with p to make it n characters (in textwidth) long. If s is already n characters long, an equal string is returned. Pad with spaces by default.

Examples

1. julia> lpad("March", 10)
2. "     March"

Julia 1.7

In Julia 1.7, this function was changed to use textwidth rather than a raw character (codepoint) count.

source

Base.rpad — Function

1. rpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> String

Stringify s and pad the resulting string on the right with p to make it n characters (in textwidth) long. If s is already n characters long, an equal string is returned. Pad with spaces by default.

Examples

1. julia> rpad("March", 20)
2. "March               "

Julia 1.7

In Julia 1.7, this function was changed to use textwidth rather than a raw character (codepoint) count.

source

Base.findfirst — Method

1. findfirst(pattern::AbstractString, string::AbstractString)
2. findfirst(pattern::AbstractPattern, string::String)

Find the first occurrence of pattern in string. Equivalent to findnext(pattern, string, firstindex(s)).

Examples

1. julia> findfirst("z", "Hello to the world") # returns nothing, but not printed in the REPL

3. julia> findfirst("Julia", "JuliaLang")
4. 1:5

source

Base.findnext — Method

1. findnext(pattern::AbstractString, string::AbstractString, start::Integer)
2. findnext(pattern::AbstractPattern, string::String, start::Integer)

Find the next occurrence of pattern in string starting at position start. pattern can be either a string, or a regular expression, in which case string must be of type String.

The return value is a range of indices where the matching sequence is found, such that s[findnext(x, s, i)] == x:

findnext("substring", string, i) == start:stop such that string[start:stop] == "substring" and i <= start, or nothing if unmatched.

Examples

1. julia> findnext("z", "Hello to the world", 1) === nothing
2. true

4. julia> findnext("o", "Hello to the world", 6)
5. 8:8

7. julia> findnext("Lang", "JuliaLang", 2)
8. 6:9

source

Base.findnext — Method

1. findnext(ch::AbstractChar, string::AbstractString, start::Integer)

Find the next occurrence of character ch in string starting at position start.

Julia 1.3

This method requires at least Julia 1.3.

Examples

1. julia> findnext('z', "Hello to the world", 1) === nothing
2. true

4. julia> findnext('o', "Hello to the world", 6)
5. 8

source

Base.findlast — Method

1. findlast(pattern::AbstractString, string::AbstractString)

Find the last occurrence of pattern in string. Equivalent to findprev(pattern, string, lastindex(string)).

Examples

1. julia> findlast("o", "Hello to the world")
2. 15:15

4. julia> findfirst("Julia", "JuliaLang")
5. 1:5

source

Base.findlast — Method

1. findlast(ch::AbstractChar, string::AbstractString)

Find the last occurrence of character ch in string.

Julia 1.3

This method requires at least Julia 1.3.

Examples

1. julia> findlast('p', "happy")
2. 4

4. julia> findlast('z', "happy") === nothing
5. true

source

Base.findprev — Method

1. findprev(pattern::AbstractString, string::AbstractString, start::Integer)

Find the previous occurrence of pattern in string starting at position start.

The return value is a range of indices where the matching sequence is found, such that s[findprev(x, s, i)] == x:

findprev("substring", string, i) == start:stop such that string[start:stop] == "substring" and stop <= i, or nothing if unmatched.

Examples

1. julia> findprev("z", "Hello to the world", 18) === nothing
2. true

4. julia> findprev("o", "Hello to the world", 18)
5. 15:15

7. julia> findprev("Julia", "JuliaLang", 6)
8. 1:5

source

Base.occursin — Function

1. occursin(needle::Union{AbstractString,AbstractPattern,AbstractChar}, haystack::AbstractString)

Determine whether the first argument is a substring of the second. If needle is a regular expression, checks whether haystack contains a match.

Examples

1. julia> occursin("Julia", "JuliaLang is pretty cool!")
2. true

4. julia> occursin('a', "JuliaLang is pretty cool!")
5. true

7. julia> occursin(r"a.a", "aba")
8. true

10. julia> occursin(r"a.a", "abba")
11. false

See also contains.

source

1. occursin(haystack)

Create a function that checks whether its argument occurs in haystack, i.e. a function equivalent to needle -> occursin(needle, haystack).

The returned function is of type Base.Fix2{typeof(occursin)}.

Julia 1.6

This method requires Julia 1.6 or later.

source

Base.reverse — Method

1. reverse(s::AbstractString) -> AbstractString

Reverses a string. Technically, this function reverses the codepoints in a string and its main utility is for reversed-order string processing, especially for reversed regular-expression searches. See also reverseind to convert indices in s to indices in reverse(s) and vice-versa, and graphemes from module Unicode to operate on user-visible “characters” (graphemes) rather than codepoints. See also Iterators.reverse for reverse-order iteration without making a copy. Custom string types must implement the reverse function themselves and should typically return a string with the same type and encoding. If they return a string with a different encoding, they must also override reverseind for that string type to satisfy s[reverseind(s,i)] == reverse(s)[i].

Examples

1. julia> reverse("JuliaLang")
2. "gnaLailuJ"

Note

The examples below may be rendered differently on different systems. The comments indicate how they’re supposed to be rendered

Combining characters can lead to surprising results:

1. julia> reverse("ax̂e") # hat is above x in the input, above e in the output
2. "êxa"

4. julia> using Unicode

6. julia> join(reverse(collect(graphemes("ax̂e")))) # reverses graphemes; hat is above x in both in- and output
7. "ex̂a"

source

Base.replace — Method

1. replace(A, old_new::Pair...; [count::Integer])

Return a copy of collection A where, for each pair old=>new in old_new, all occurrences of old are replaced by new. Equality is determined using isequal. If count is specified, then replace at most count occurrences in total.

The element type of the result is chosen using promotion (see promote_type) based on the element type of A and on the types of the new values in pairs. If count is omitted and the element type of A is a Union, the element type of the result will not include singleton types which are replaced with values of a different type: for example, Union{T,Missing} will become T if missing is replaced.

See also replace!, splice!, delete!, insert!.

Julia 1.7

Version 1.7 is required to replace elements of a Tuple.

Examples

1. julia> replace([1, 2, 1, 3], 1=>0, 2=>4, count=2)
2. 4-element Vector{Int64}:
3. 0
4. 4
5. 1
6. 3

8. julia> replace([1, missing], missing=>0)
9. 2-element Vector{Int64}:
10. 1
11. 0

source

1. replace(s::AbstractString, pat=>r, [pat2=>r2, ...]; [count::Integer])

Search for the given pattern pat in s, and replace each occurrence with r. If count is provided, replace at most count occurrences. pat may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring (when pat is a AbstractPattern or AbstractString) or character (when pat is an AbstractChar or a collection of AbstractChar). If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text. To remove instances of pat from string, set r to the empty String ("").

Multiple patterns can be specified, and they will be applied left-to-right simultaneously, so only one pattern will be applied to any character, and the patterns will only be applied to the input text, not the replacements.

Julia 1.7

Support for multiple patterns requires version 1.7.

Examples

1. julia> replace("Python is a programming language.", "Python" => "Julia")
2. "Julia is a programming language."

4. julia> replace("The quick foxes run quickly.", "quick" => "slow", count=1)
5. "The slow foxes run quickly."

7. julia> replace("The quick foxes run quickly.", "quick" => "", count=1)
8. "The  foxes run quickly."

10. julia> replace("The quick foxes run quickly.", r"fox(es)?" => s"bus\1")
11. "The quick buses run quickly."

13. julia> replace("abcabc", "a" => "b", "b" => "c", r".+" => "a")
14. "bca"

source

Base.split — Function

1. split(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
2. split(str::AbstractString; limit::Integer=0, keepempty::Bool=false)

Split str into an array of substrings on occurrences of the delimiter(s) dlm. dlm can be any of the formats allowed by findnext‘s first argument (i.e. as a string, regular expression or a function), or as a single character or collection of characters.

If dlm is omitted, it defaults to isspace.

The optional keyword arguments are:

  • limit: the maximum size of the result. limit=0 implies no maximum (default)
  • keepempty: whether empty fields should be kept in the result. Default is false without a dlm argument, true with a dlm argument.

See also rsplit.

Examples

1. julia> a = "Ma.rch"
2. "Ma.rch"

4. julia> split(a, ".")
5. 2-element Vector{SubString{String}}:
6. "Ma"
7. "rch"

source

Base.rsplit — Function

1. rsplit(s::AbstractString; limit::Integer=0, keepempty::Bool=false)
2. rsplit(s::AbstractString, chars; limit::Integer=0, keepempty::Bool=true)

Similar to split, but starting from the end of the string.

Examples

1. julia> a = "M.a.r.c.h"
2. "M.a.r.c.h"

4. julia> rsplit(a, ".")
5. 5-element Vector{SubString{String}}:
6. "M"
7. "a"
8. "r"
9. "c"
10. "h"

12. julia> rsplit(a, "."; limit=1)
13. 1-element Vector{SubString{String}}:
14. "M.a.r.c.h"

16. julia> rsplit(a, "."; limit=2)
17. 2-element Vector{SubString{String}}:
18. "M.a.r.c"
19. "h"

source

Base.strip — Function

1. strip([pred=isspace,] str::AbstractString) -> SubString
2. strip(str::AbstractString, chars) -> SubString

Remove leading and trailing characters from str, either those specified by chars or those for which the function pred returns true.

The default behaviour is to remove leading and trailing whitespace and delimiters: see isspace for precise details.

The optional chars argument specifies which characters to remove: it can be a single character, vector or set of characters.

See also lstrip and rstrip.

Julia 1.2

The method which accepts a predicate function requires Julia 1.2 or later.

Examples

1. julia> strip("{3, 5}\n", ['{', '}', '\n'])
2. "3, 5"

source

Base.lstrip — Function

1. lstrip([pred=isspace,] str::AbstractString) -> SubString
2. lstrip(str::AbstractString, chars) -> SubString

Remove leading characters from str, either those specified by chars or those for which the function pred returns true.

The default behaviour is to remove leading whitespace and delimiters: see isspace for precise details.

The optional chars argument specifies which characters to remove: it can be

(本文超出站点单文档体积上限,已截断)