Julia “string” and methods()
Last Updated on September 19, 2022 by Editorial Team
Author(s): Vivek Chaudhary
Originally published on Towards AI the World’s Leading AI and Technology News and Media Company. If you are building an AI-related product or service, we invite you to consider becoming an AI sponsor. At Towards AI, we help scale AI and technology startups. Let us help you unleash your technology to the masses.
The objective of this article is to understand string-type variables in Julia Programming and various operations associated with them.
Strings in Julia are defined in “double quotes”.
- Declare a string variable s1.
s1=”hello world”
println(s1)
print(typeof(s1)) #to check the datatype of variable
Output:
hello world
String
2. String Concatenation
s1=”hello vivek”
s2=”welcome to julia tutorial”
#using * operator
println(s1*’ ‘*s2)
#using string function
println(string(s1,’ ‘,s2))
Output:
"*": hello vivek welcome to julia tutorial
"string": hello vivek welcome to julia tutorial
3. String Index and Slicing
Index in Julia data types starts from 1 unlike python where it starts from 0
First, check what happens if we search for an item with Index 0.
println(s1[0])
Output:
BoundsError: attempt to access 40-codeunit String at index [0]
Stacktrace:
[1] checkbounds
@ .\strings\basic.jl:216 [inlined]
[2] codeunit
@ .\strings\string.jl:102 [inlined]
[3] getindex(s::String, i::Int64)
@ Base .\strings\string.jl:223
[4] top-level scope
@ In[4]:5
[5] eval
@ .\boot.jl:373 [inlined]
[6] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1196
The usual way of searching items in a Julia string:
println(“item as pos 5 is“,s1[5])
println(“item as pos 9 is“,s1[9])
Output:
item as pos 5 is o
item as pos 9 is v
Slicing: Julia uses keywords “begin” and “end” to fetch the first and last item from a string.
s1=”hello vivek welcome to julia programming”
println("first item of string s1 is:",s1[begin])
println("last item of string s1 is:",s1[end])
Output:
first item of string s1 is: h
last item of string s1 is: g
#slicing
println(s1[begin:begin+10])
println(s1[begin+6:begin+18])
println(s1[begin:end-21])
println(s1[begin+6:length(s1)-12])
Output:
hello vivek
vivek welcome
hello vivek welcome
vivek welcome to julia
#negative Indexing
println(s1[end-3])
println(s1[7:end-12])
println(s1[end-10:end])
Output:
m
vivek welcome to julia
programming
4. String Interpolation
Interpolation is the process of executing whatever is executable in a string in Julia executable is mentioned by “$.”
s1=”vivek”
s2=”80"
println(“hello $s1, you scored $s2”)
Output:
hello vivek, you scored 80
5. String Comparison
println(cmp(“a”,”a”)) #returns 0 when output is true
println(cmp(“def”,”abc”)) #returns 1 when output is false
Output:
0
1
println(cmp('a',"a"))
Output:
MethodError: no method matching isless(::Char, ::String)
Closest candidates are:
isless(::AbstractString, ::AbstractString) at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\base\strings\basic.jl:344
isless(::Any, ::Missing) at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\base\missing.jl:88
isless(::Missing, ::Any) at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\base\missing.jl:87
...
Stacktrace:
[1] cmp(x::Char, y::String)
@ Base .\operators.jl:467
[2] top-level scope
@ In[22]:2
[3] eval
@ .\boot.jl:373 [inlined]
[4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1196
‘single quotes’ represents char datatype
“double quotes” represents string type
6. String search operations
startswith()
s1=”hi geeks enjoying learning julia”
println(startswith(s1,’h’))
println(startswith(s1,’g’))
println(startswith(s1,”hi”))
println(startswith(s1,”julia”))
Output:
true
false
true
false
endswith()
s1=”hi geeks enjoying learning julia”
println(endswith(s1,’a’))
println(endswith(s1,’h’))
println(endswith(s1,”julia”))
println(endswith(s1,”learning”))
Output:
true
false
true
false
startswith() and endswith() can perform char and pattern searching.
findfirst() and findlast(): find the occurrence of the item and returns the position.
s1=”hi geeks enjoying learning julia”
#findfirst()
println(findfirst(‘j’,s1)) --> 12
println(findfirst(“geeks”,s1)) --> 4:8
#findlast()
println(findlast(‘j’,s1)) --> 28
println(findlast(‘e’,s1)) -->20
s2="hello vivek, Does vivek like julia?"
println("find vivek from first: ",findfirst("vivek",s2))
println("find vivek from last: ",findlast("vivek",s2))
Output:
find vivek from first: 7:11
find vivek from last: 19:23
findnext(): takes three arguments findnext(pattern,string,position to look from)
#findnext()
println(findnext(‘e’,s1,7))
println(findnext(‘j’,s1,findfirst(‘j’,s1)))
Output:
10
12
findprev()– takes three arguments findnext(pattern,string,position to look from)
#findprev()
println(findprev(‘e’,s1,18))
Output:
10
7. String strip
strip(), lstrip() and rstrip()
#strip()
println("length of string with whitespace: ",length(" vivek "))
println("length of string without whitespace: ",length(strip(" vivek ")))
println(strip(" vivek "))
println(strip("sviveks",'s'))
Output:
length of string with whitespace: 10
length of string without whitespace: 5
vivek
vivek
#lstrip()
#lstrip
println("length of string with whitespace: ",length(" vivek "))
println("length of string without whitespace: ",length(lstrip(" vivek ")))
println(lstrip(" vivek",' '))
println(lstrip("sviveks",'s'))
Output:
length of string with whitespace: 10
length of string without whitespace: 7
vivek
viveks
#rstrip()
println("length of string with whitespace: ",length(" vivek "))
println("length of string without whitespace: ",length(rstrip(" vivek ")))
println(rstrip(" vivek",' '))
println(rstrip("sviveks",'s'))
Output:
length of string with whitespace: 10
length of string without whitespace: 8
vivek
svivek
8. split() and join()
split() — separates the string into an array of items on the basis of a Separator.
join() — joins the array items to create a string
#split()
println(split("vivek#learning#julia#python",'#'))
#split the string into 3 array item
sprintln(split(“vivek learning julia and python”,’ ‘,limit=3))
Output:
SubString{String}["vivek", "learning", "julia", "python"]
SubString{String}["vivek", "learning", "julia and python"]
#join()
#join() similar to pythin join func
#join()- joins array of strings into string
l=["hello","julia","learners"]
println("joined string--> ",join(l,"##"))
Output:
joined string--> hello##julia##learners
9. substr()- to extract a part of the string
#substring()
s1="hi geeks enjoying learning julia"
println(SubString(s1,4,17))
println(SubString(s1,10,26))
Output:
geeks enjoying
enjoying learning
10. sort() — method works on an array of elements to sort the items in ascending or descending fashion. To sort a string, it is cast into an array using collect(), and then sort() is applied, and then it is converted back to a string using join().
#sort() and collect()
println("output of sort -->",sort(collect("vivek")))
println("sorted array converted back to string-->", join(sort(collect("vivek"))))
println("sorted array converted back to string reverse-->", join(sort(collect("vivek"),rev=true)))
Output:
output of sort -->['e', 'i', 'k', 'v', 'v']
sorted array converted back to string-->eikvv
sorted array converted back to string reverse-->vvkie
To Summarize:
- Julia strings and string methods.
Thanks for reading my blog and supporting the content. Appreciation always helps to keep up the spirit. I will try my best to keep coming up with quality content. Connect with me to get updates about upcoming new content.
Keep Supporting.
Julia “string” and methods() was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.
Join thousands of data leaders on the AI newsletter. It’s free, we don’t spam, and we never share your email address. Keep up to date with the latest work in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.
Published via Towards AI