Lecture 9.1: Strings
Lecture 9.1: Strings
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
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
}
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)
}
}
However, you can reassign a string variable again if you declared the variable using keyword var. (Remember:
Kotlin var Vs val).
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).
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
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
Kotlin has an awesome feature called string templates that allows strings to contain template expressions.
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.
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(){
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")}
In this lecture, you'll learn about functions; what functions are, its syntax
and how to create a user-function in Kotlin.
KOTLIN FUNCTIONS
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)}")
}
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
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
}
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
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
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 sum(){
var num1 =5
var num2 = 6
println("sum = "+(num1+num2))
}
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”