10.2. String Functions#
Julia defines a number of functions that operate on strings. For example,
lowercase
and uppercase
converts all letters to lower- or upper-case:
println(uppercase("julia123 ") * lowercase("LOWER"))
JULIA123 lower
The titlecase
commands capitalizes the first character of each word in a string:
str = "SEARCHING FOR CHARACTERS AND SUBSTRINGS"
titlecase(str)
"Searching For Characters And Substrings"
10.2.1. Searching for characters and substrings#
The ∈ operator (type “\in” and tab) returns true
if a characters appears in a string:
'!' ∈ str
false
The function findfirst(pattern, str)
returns the indices of the first occurance of pattern
in str
:
str = "Hello, World! These are my words."
pattern = "wor"
idx1 = findfirst(pattern, lowercase(str))
8:10
The function findnext(pattern, str, start)
returns the indicies of the next occurance of pattern
in str
after the one at position start
:
idx2 = findnext(pattern, lowercase(str), idx1[end])
28:30
Similarly, findlast
and findprev
starts from the end of the string.
10.2.2. Replacing substrings#
The function replace(str, pattern=>repl)
searches the string str
for all occurances of the substring pattern
, and replace them with the string repl
:
println(str)
println(replace(str, ", World"=>" there"))
Hello, World! These are my words.
Hello there! These are my words.
10.2.3. Converting strings#
The function parse(Type, string; base)
lets you parse a string that contains a number into the actual number.
parse(Int, "1234")
1234
parse(Int, "011010", base = 2)
26
parse(Float64, "1.2e-3")
0.0012
This function is particularly useful when parsing input files containing numbers.
strings = ["123.4", "4590.12", "0.456"]
parse.(Float64, strings)
3-element Vector{Float64}:
123.4
4590.12
0.456