Julia Strings

A String is a finite sequence of characters.

In this tutorial, we will learn how to initialize a String and some of the basic operations with Strings like concatenation and interpolation.

Initialization

String literals are defined with the string in double quotes " " or triple double quotes """ """.

script.jl

s1 = "I am a string."
println(s1)
s2 = """I am also a string."""
println(s2)

Output

I am a string.
I am also a string.
ADVERTISEMENT

Concatenate Strings

You can concatenate two or more Strings in Julia using string(str1, str2, ...) function.

In this example, we will concatenate two strings.

script.jl

s1 = "There are seven continents";
s2 = " and five oceans.";
s3 = string(s1, s2)
println(s3)

Output

There are seven continents and five oceans.

In this example, we take four strings and concatenate them in a single statement.

script.jl

s1 = "There are seven continents";
s2 = " and five oceans.";
s3 = " This is third string.";
s4 = " This is fourth.";
resultStr = string(s1, s2, s3, s4)
println(resultStr)

Output

There are seven continents and five oceans. This is third string. This is fourth.

String Interpolation

Dollar sign $ can be used to insert existing variables into a string literal and evaluate expressions within the string itself.

script.jl

a = 7
b = 5
str = "a is $a. b is $b. a*b is $(a*b)";
println(str)

Output

a is 7. b is 5. a*b is 35

In this example, we have done an arithmetic operation inside the string using string interpolation.

Conclusion

In this Julia Tutorial, we learned about Strings in Julia, how to initialize a string, interpolate a string, etc.