Strings-Lists - Week20part3 - Block-A, B, C
Strings-Lists - Week20part3 - Block-A, B, C
Computer Programming
1
Objectives
Appreciate how methods can be executed in
Scala
2
Using methods in Scala
The Scala library contains methods such as main,
println and readInt that allow us to carry out
different tasks in our program.
H E L L O
0 1 2 3 4
"HELLO".indexOf("E") //1
"HELLO".charAt(0) //H
4
Common String methods
There are two overloaded substring methods.
"HELLO".substring(0,2) //HE (2nd argument exclusive)
"HELLO".substring(2) //LLO
x.substring(3).substring(3).substring(3)
x.substring(0,10).substring(3).toUpperCase
x.charAt(x.indexOf("H")+2)
5
Lists of data
The List data type allows us to hold a collection of
data of any type, e.g. A list of numbers or strings.
List.range(1,11) //contains 1 - 10
List.fill(3)(5) //contains 5,5,5
List.fill(5)(3) //contains 3,3,3,3,3
List.fill(3)("foo") //contains foo,foo,foo
7
Using List methods
The List type offers a wealth of methods, e.g.
take – takes elements from start of list
takeRight – takes elements from end of list
drop – drops elements from start of list
dropRight – drops elements from end of list
x.tail.tail.reverse //List(5,4,3)
x.takeRight(4).take(3).head //2
x.take(4).dropRight(1).tail //List(2,3)
8
Summary
Strings and Lists offer a wealth of useful methods that
can be used to conduct a variety of tasks and help to
solve common problems.
9
Suggested reading
Online Tutorials:
https://www.tutorialspoint.com/scala/
http://docs.scala-lang.org/
https://alvinalexander.com/scala/scala-programming-cookbook
-recipes-faqs
Textbooks:
Programming in Scala (3rd edition) by Martin Odersky
An Introduction to programming and problem-solving using
Scala (2nd edition) by Mark C. Lewis and Lisa L. Lacher
10