0% found this document useful (0 votes)
64 views42 pages

Lecture 9.1: Strings

This document provides an overview of strings in Kotlin, including: 1) How to declare and initialize string variables 2) How to access characters within a string using indexing 3) That strings are immutable in Kotlin 4) How to iterate through the characters of a string using a for loop 5) Details about string literals, including escaped strings and raw strings

Uploaded by

Osama Alkhatib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views42 pages

Lecture 9.1: Strings

This document provides an overview of strings in Kotlin, including: 1) How to declare and initialize string variables 2) How to access characters within a string using indexing 3) That strings are immutable in Kotlin 4) How to iterate through the characters of a string using a for loop 5) Details about string literals, including escaped strings and raw strings

Uploaded by

Osama Alkhatib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

LECTURE 9.

1: STRINGS
BY LINA HAMMAD & AHMAD BARGHASH

In this lecture, you will learn about how to declare, use and manipulate strings in Kotlin, string
templates, and few commonly used string properties and functions with the help of examples.
KOTLIN STRING

 Strings are a arrays of characters. For example, "Hello there!".


 In Kotlin, all strings are objects of String class.
HOW TO CREATE A STRING VARIABLE?

 To define a String variable in Kotlin use the " "


val myString = "Hey there!"

 Here, myString is a variable of type String.

 Also, you can declare variable of type String and specify its type in one statement and initialize the variable in
another statement later in the program.
val myString: String
... .. ...
myString = "Howdy"
HOW TO ACCESS CHARACTERS OF A STRING?

 To access elements (character) of a string, index access operator is used. For example,

fun main() {
val myString = "Hey there!"
val item = myString[2]

 Here, item variable contains y, third character of the myString string. It's because indexing in Kotlin starts from 0
not 1.
fun main() {
val myString = "Hey there!"
var item: Char

item = myString[0] // item contains 'H'


item = myString[9] // item contains '!'
item = myString[10] // Error! String index is out of range
item = myString[-1] // Error! String index is out of range

}
EXAMPLE: ITERATE THROUGH A STRING

 If you need to iterate through elements of a string, you can do it easily by using a for loop.

fun main() {
val myString = "Hey!"
for (item in myString) {
println(item)
}
}

The output is:


H
e
y
!
STRINGS IN KOTLIN ARE IMMUTABLE
 Like Java, strings are immutable in Kotlin. This means, you cannot change individual character of a string. For
example, fun main() {
var myString = "Hey!"
myString[0] = 'h' // Error! Strings
}

 However, you can reassign a string variable again if you declared the variable using keyword var. (Remember:
Kotlin var Vs val).

fun main(args: Array<String>) {


var myString = "Hey!" The output is:
println("myString = $myString")
myString = "Hello!" myString = Hey!
println("myString = $myString") myString = Hello!
}
STRING LITERALS

 A literal is the source code representation of a fixed value. For example, "Hey there!" is a string literal that
appears directly in a program without requiring computation (like variables).

 There are two types of string literals in Kotlin:


1. Escaped string
2. Raw String
ESCAPED STRING
 A escaped string may have escaped characters in them. For example, \n is an escape character which inserts a
newline in the text where it appears.

val myString = "Hey there!\n"

 Here is a list of escape characters supported in Kotlin:


 \t - Inserts tab
 \b - Inserts backspace
 \n - Inserts newline
 \r - Inserts carriage return (Send the beginning of the line)
 \' - Inserts single quote character
 \" - Inserts double quote character
 \\ - Inserts backslash
 \$ - Inserts dollar character
RAW STRING

 A raw string can contain newlines (not new line escape character) and arbitrary text. A raw string is delimited by
a triple quote """. For example,
fun main(args: Array<String>) { The output is:
val myString = """
for (character in "Hey!")
for (character in "Hey!")
println(character) println(character)
"""
print(myString)
}

 You can remove the leading whitespaces of a raw string using trimMargin() function.
EXAMPLE: PRINTING RAW STRING

fun main() { The output is:


println("Output without using trimMargin function:")
val myString = """ Output without using trimMargin function:
|Kotlin is interesting.
|Kotlin is sponsored and developed by JetBrains.
""" |Kotlin is interesting.
println(myString) |Kotlin is sponsored and developed by JetBrains.
println("Output using trimMargin function:\n")
println(myString.trimMargin())
} Output using trimMargin function:

Kotlin is interesting.
Kotlin is sponsored and developed by JetBrains.

 By default, trimMargin() function uses | as margin prefix. However, you can change it by passing a new string to
this function.
EXAMPLE: TRIMMARGIN() WITH ARGUMENT

fun main(args: Array<String>) {


val myString = """
!!! Kotlin is interesting.
!!! Kotlin is sponsored and developed by JetBrains.
"""
println(myString.trimMargin("!!! "))
}

The output is:


Kotlin is interesting.
Kotlin is sponsored and developed by JetBrains.
KOTLIN STRING TEMPLATES

 Kotlin has an awesome feature called string templates that allows strings to contain template expressions.

 A string template expression starts with a dollar sign $.


EXAMPLE: KOTLIN STRING TEMPLATE

fun main(args: Array<String>) {


val myInt = 5;
val myString = "myInt = $myInt"
println(myString)
}

The output is:


myInt = 5

 It is because the expression $myInt (expression starting with $ sign) inside the string is evaluated and
concatenated into the string.
FEW STRING PROPERTIES AND FUNCTIONS
 Since literals in Kotlin are implemented as instances of String class, you can use several methods and properties of
this class.

 length property - returns the length of character sequence of a string.


 compareTo function - compares this String (object) with the specified object. Returns 0 if the object is equal to
the specified object.
 get function - returns character at the specified index. You can use index access operator [ ], instead of get
function as index access operator internally calls get function.
 plus function - returns a new string which is obtained by the concatenation of this string and the string passed to
this function.You can use + operator instead of plus function as + operator calls plus function under the hood.
 subSequence Function - returns a new character sequence starting at the specified start and end index.
EXAMPLE: STRING PROPERTIES AND FUNCTION
fun main(args: Array<String>) {
val s1 = "Hey there!"
val s2 = "Hey there!"

var result: String


println("Length of s1 string is ${s1.length}.")
result = if (s1.compareTo(s2) == 0) "equal" else "not equal"
println("Strings s1 and s2 are $result.")

// s1.get(2) is equivalent to s1[2]


println("Third character is ${s1.get(2)}.")
result = s1.plus(" How are you?") // result = s1 + " How are you?"
println("result = $result")
println("Substring is \"${s1.subSequence(4, 7)}\"")
}

The output is:


Length of s1 string is 10.
Strings s1 and s2 are equal.
Third character is y.
result = Hey there! How are you?
Substring is "the
EXAMPLE 1: COMPARING STRINGS
fun main() { fun main(args: Array<String>) {
val style = "Kotlin" val style = "Kotlin"
val style2 = "Kotlin" val style2 = "Kotlin"
if (style == style2) if (style.equals(style2))
println("Equal") println("Equal")
else else
println("Not Equal") println("Not Equal")
} }

The output is: The output is:


Equal Equal

 In the above program, we've two strings style and style2. We simply use equality operator (==) or method equals
to compare the two strings, which compares the value Kotlin to Kotlin and prints Equal.
EXAMPLE 4: COMPARING STRINGS

fun main(){ fun main(){


var str1 = "B"
var str1 = "BeginnersBook" var str2 = "b"
var str2 = "beginnersbook" println("String Equals? : ${str1.compareTo(str2)}")
println("String Equals? : ${str1.compareTo(str2)}") }
}

The output is: The output is:


String Equals? : -32 String Equals? : -32
EXAMPLE 5: SUBSTRINGS AND CONTAIN STRING
fun main(){

var str = “MobileApplication" The output is:


Index from 2 to 5: bil
println("Index from 2 to 5: " +str.subSequence(2,5))
}

fun main(){

var str = “GJU.EDU.JO"


The output is:
Contains GJU.: true
println("Contains GJU.: ${str.contains("GJU.")}")
}
EXAMPLE 6: STRING REPLACEMENT
fun main(args: Array<String>) {
var sentence = "T his is b ett er."
println("Original sentence: $sentence")
sentence = sentence.replace("\\s".toRegex(), "")
println("After replacement: $sentence")
}

The output is:


Original sentence: T his is b ett er.
After replacement: Thisisbetter.

 In the aboe program, we use String's replaceAll() method to remove and replace all whitespaces in the string sentence.
 We've used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the
string. Then, we replace it with "" (empty string literal).
EXAMPLE 7: STRING REPLACEMENT
fun main(args: Array<String>) { fun main(args: Array<String>) {
var sentence = "Tomorrow" var sentence = "Tomorrow"
println("Original sentence: $sentence") println("Original sentence: $sentence")
sentence = sentence.replace("^T".toRegex(), "t") sentence = sentence.replace("w$".toRegex(), "WW")
println("After replacement: $sentence")} println("After replacement: $sentence")}

The output is: The output is:


Original sentence: Tomorrow Original sentence: Tomorrow
After replacement: tomorrow After replacement: TomorroWW
EXAMPLE 8: STRING REPLACEMENT
fun main(args: Array<String>) {
var sentence = "Tomorrow" The output is:
println("Original sentence: $sentence")
sentence = sentence.replace("[A-Za-z]".toRegex(), "9") Original sentence: Tomorrow
println("After replacement: $sentence")}
After replacement: 99999999

fun main(args: Array<String>) {


The output is:
var sentence = "Tomorrow"
println("Original sentence: $sentence") Original sentence: Tomorrow
sentence = sentence.replace("[A-Za-z]{1,}".toRegex(), "9")
println("After replacement: $sentence")} After replacement: 9
EXAMPLE 9: STRING REPLACEMENT

fun main(args: Array<String>) { fun main(args: Array<String>) {


var sentence = "Tomorrow" var sentence = "Tomorrow"
println("Original sentence: $sentence") println("Original sentence: $sentence")
sentence = sentence.replace("or.*".toRegex(), "oooooo") sentence = sentence.replace(“o..o".toRegex(), “rrrr")
println("After replacement: $sentence")} println("After replacement: $sentence")}

The output is:


The output is:
Original sentence: Tomorrow
Original sentence: Tomorrow
After replacement: Tomrrrrw
After replacement: Tomoooooo
LECTURE 9.2: FUNCTIONS
BY LINA HAMMAD & AHMAD BARGHASH

In this lecture, you'll learn about functions; what functions are, its syntax
and how to create a user-function in Kotlin.
KOTLIN FUNCTIONS

 In programming, function is a group of related statements that perform a specific task.


 Functions are used to break a large program into smaller and modular chunks.
 Dividing a complex program into smaller components makes our program more organized, reusable, manageable
and it avoids code repetition.
 For example lets say we have to write three lines of code to find the average of two numbers, if we create a
function to find the average then instead of writing those three lines again and again, we can just call the function
we created.
TYPES OF FUNCTION IN KOTLIN

 There are two types of functions in Kotlin:


1. Standard Library Function
2. User-defined functions
STANDARD LIBRARY FUNCTION

 The standard library functions are built-in functions in Kotlin that are readily available for use. For example,
1. print() is a library function that prints message to the standard output stream (monitor).
2. sqrt() returns square root of a number (Double value)
 So, The functions that are already present in the Kotlin standard library are called standard library functions
or built-in functions or predefined functions.
STANDARD LIBRARY FUNCTION EXAMPLE
fun main(args: Array<String>) {
var number = 5.5
print("Result = ${Math.sqrt(number)}")
}

The output is:


Result = 2.345207879911715

 Here, sqrt() is a library function which returns square root of a number (Double value).
 print() library function which prints a message to standard output stream.
USER-DEFINED FUNCTIONS

 A user defined function is a function which is created by user.


 For example, lets say we want a function to check even or odd number in our program then we can create a
function for this task and later call the function where we need to perform the check.
 User defined function might take parameter(s), perform an action and might return the result of that action
as a value.
 Kotlin functions are declared using the fun keyword.
HOW TO CREATE A USER-DEFINED FUNCTION IN KOTLIN?

 Before you can use (call) a function, you need to define it.
 Here's how you can define a function in Kotlin:

fun callMe() {
// function body
}

 To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the
name of the function is callMe.
 In the above program, the parenthesis ( ) are empty. It means, this function doesn't require any argument to work.
 The codes inside curly braces { } is the body of the function.
HOW TO CALL A FUNCTION?
 You have to call the function to run codes inside the body of the function. Here's how:

fun main() {
callMe() // call the function
}

 This statement calls the callMe() function declared earlier.


EXAMPLE 1: SIMPLE FUNCTION PROGRAM
fun callMe() {
println("Is")
println("Fun")
}

fun main(args: Array<String>) {


callMe()
println("Kotlin")
}

The output is:


Is
Fun
Kotlin

 The callMe() function in the above code doesn't accept any argument.
 Also, the function doesn't return any value.
EXAMPLE 2: SIMPLE FUNCTION PROGRAM

//Created the function


fun sayHello(){
println("Hello")
}

fun main(args : Array<String>){


//Calling the function
sayHello()
}

The output is:


Hello
USER DEFINED FUNCTION WITH ARGUMENTS AND RETURN TYPE

 Functions are also taking parameter as arguments and return value. Parameters in function are separated using
commas.

 If a function does not returns any value than its return type is Unit (Similar to void in other languages). It is optional
to specify the return type of function definition which does not returns any value.

 Syntax:
fun function_name(param1: data_type, param2: data_type, ...): return_type
EXAMPLE: ADD TWO NUMBERS USING FUNCTION

fun addNumbers(n1: Double, n2: Double): Int {


val sum = n1 + n2
val sumInteger = sum.toInt()
return sumInteger
}
fun main(args: Array<String>) {
val number1 = 12.2
val number2 = 3.4
val result: Int
result = addNumbers(number1, number2)
println("result = $result")
}

In the program, sumInteger is returned from addNumbers()


The output is: function to the variable result in the main function.
Result = 15
HOW FUNCTIONS WITH ARGUMENTS AND RETURN VALUE WORK?
 Here, two arguments number1 and number2 of type Double are passed to the addNumbers() function during
function call. These arguments are called actual arguments.
result = addNumbers(number1, number2)

 The parameters n1 and n2 accepts the passed arguments (in the function definition). These arguments are called
formal arguments (or parameters).
HOW FUNCTIONS WITH ARGUMENTS AND RETURN VALUE WORK?
 In Kotlin, arguments are separated using commas. Also, the type of the formal argument must be explicitly typed.
 Note that, the data type of actual and formal arguments should match, i.e., the data type of first actual argument
should match the type of first formal argument. Similarly, the type of second actual argument must match the type
of second formal argument and so on.

 Here,
return sumInteger

is the return statement. This code terminates the addNumbers() function, and control of the program jumps to
the main() function.
 In the program, sumInteger is returned from addNumbers() function. This value is assigned to the variable result.
HOW FUNCTIONS WITH ARGUMENTS AND RETURN VALUE WORK?

 Notice,
 both sumInteger and result are of type Int.
 the return type of the function is specified in the function definition.
 If the function doesn't return any value, its return type is Unit. It is optional to specify the return type in the
function definition if the return type is Unit.
OPTION 1 OF FUNCTION BODY

fun main(args: Array<String>) {


println(getName("Kotlin", "Functions"))
}

fun getName(firstName: String, lastName: String): String {


var name = "$firstName $lastName"
return name
}

The output is:


Kotlin Functions
OPTION 2 OF FUNCTION BODY

fun main(args: Array<String>) {


println(getName("Kotlin", "Functions"))
}

fun getName(firstName: String, lastName: String): String {


return "$firstName $lastName"
}

The output is:


Kotlin Functions
OPTION 3 OF FUNCTION BODY

fun main(args: Array<String>) {


println(getName("Kotlin", "Functions"))
}

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

The output is:


Kotlin Functions
OPTION TO RETURN VALUE
fun main(args: Array<String>){
sum()
print("code after sum")
}

fun sum(){
var num1 =5
var num2 = 6
println("sum = "+(num1+num2))
}

The output is:


sum = 11
code after sum
ASSIGNMENT 1

 Write a program that test the credentials of the user in an encrypted way. The user should enter the user name
and password.Your program should send the user name to function CheckUserName which Must add “2” to the
beginning of the username and the end of it. Then, the function should check if the resulted string is “2kotlin2” to
return “OK” or any other string to return “No”. Similarly, The password should be sent to the function
CheckPassword that transfers any substring “fun” into FUN (if available) then check if the resultant string is
aaFUNbb to return “OK” and returns “No” on any other resultant string. If the main function made sure that
both user name and password are correct, it should print “You are authorized”

You might also like