In this tutorial, we’ll be discussing at length an important data type of Kotlin, namely Kotlin String. It’s recommended to read Introduction to Kotlin tutorial before proceeding ahead.
Kotlin String
String is an array of characters. Kotlin Strings are more or less similar to the Java Strings, but with some new add-ons. Following is the syntax to define a string.
var str: String = "Hello"
//or
var str = "Hello"
var newString: String = 'A' //ERROR
var newString: String = 2 //ERROR
String in Kotlin is implemented using the String
class. Like Java String, Kotlin Strings are immutable.
var str = "Hello"
str += "Kotlin Strings"
The above declaration changes the reference of the variable str
in the second line to the newly created string(“Hello Kotlin Strings”) in the String Pool.
Creating an empty String
var s = String() //creates an empty string.
Unlike Java, Kotlin doesn’t require a new
keyword to instantiate an object of a class.
Important Properties and Functions of Kotlin String
length
: This is a property that can be accessed using the dot operator on the String. Returns the number of characters present in a string.val str = "Hello Kotlin Strings" println(str.length) //prints 20
get(index)
: Returns the character specified at the particular index.subSequence(startIndex, endIndex)
: Returns the substring between thestartIndex
and theendIndex
but excluding the endIndex character.val str = "Hello Kotlin Strings" println(str.subSequence(0,5)) //prints Hello
a.compareTo(b)
: If a is equal to b, it returns 0, if a<b it returns positive number. compareTo accepts another argument too, namelyignoreCase
.var str = "Hello Kotlin Strings" var s = String() s = "Hello KOTLIN Strings" println(s.compareTo(str)) //prints -32 println(s.compareTo(str,true)) //prints 0
Accessing Characters in a String
To access individual characters of a String, Kotlin supports the index access operator(Unlike Java) as shown below.
Using Index Operator
var str = "Hello, Kotlin"
print(str[0]) //prints H
Using the get method
val str = "Hello Kotlin Strings"
println(str.get(4)) //prints o
Iterating through a String
We can loop through a string to access each character using a for-in loop as shown below.
for(element in str){
println(element)
}
Escape characters in Kotlin Strings
Following are the escape characters that when used with a backslash behave differently.
n
newline.r
carriage return.t
tab.b
backspace"
double quote'
single quote\
backslash$
dollar – Dollar symbol is used in String templates that we’ll be seeing next
String Templates
Instead of concatenating an expression in a string, Strings can contain expressions/statements following a dollar symbol as shown below.
var len = str.length
var newStr = "Length of str is ${str.length}"
//or
var newStr = "Length of str is $len"
println(Length of str is ${str.length})
Using string templates, we can insert variables and expressions in a string. String Templates are commonly used in print
statements.
To use the $ symbol in a string we need to escape the character.
var escapedDollar = "Amount is $5.50"
print(escapedDollar) //prints Amount is $5.50
Raw Strings – Multiline String
Raw strings are strings placed inside triple quotes. We don’t have to escape characters in triple-quoted strings. These strings can be used in multi lines without the need to concatenate each line.
var rawString = """Hi How you're Doing
I'm doing fine.
I owe you $5.50"""
print(rawString)
//Prints the following in the console
Hi How you're Doing
I'm doing fine.
I owe you $5.50
Note: Since escape characters are not parsed, adding a n or t won’t have any effect.
var rawString = """Hi How you're Doing
I'm doing finen.
I owe you $5.50"""
print(rawString)
//prints the following
Hi How you're Doing
I'm doing finen.
I owe you $5.50
Raw strings are handy when you need to specify a file/directory path in a string.
We can indent raw strings or remove the whitespacing in multi-lines using the function trimMargin()
.
var rawString = """Hi How you're Doing
|I'm doing fine.
|I owe you $5.50""".trimMargin("|")
print(rawString)
//Prints the following to the console.
Hi How you're Doing
I'm doing fine.
I owe you $5.50
Note: We can’t pass a blank string as the trim margin. The trimMargin()
function trims the string till the marginPrefix specified.
String templates and Raw Strings can be combined together as shown below.
var str = "Kotlin"
var rawString = """Hi How you're Doing $str
|I'm doing fine.
|I owe you $5.50""".trimMargin("|")
print(rawString)
//The following gets printed on the console
Hi How you're Doing Kotlin
I'm doing fine.
I owe you $5.50
Overriding String method
In Java, we commonly override toString() method of a class to display the contents of the class’s instance object. Similar stuff happens in Kotlin too as shown below.
class Student(var name: String, var age: Int)
{
//Define properties and functions here.
}
//The following code is written inside the main function of the Kotlin class.
var student = Student("Anupam", 23)
print(student) //prints [email protected]
Printing the above object doesn’t give any idea about the variables initialised.
Here’s where we override the toString()
method as shown below.
class Student(var name: String, var age: Int)
{
override fun toString(): String {
return "Student name is $name and age is $age"
}
}
//The following code is written inside the main function of the Kotlin class.
var student = Student("Anupam", 23)
print(student) //prints Student name is Anupam and age is 23
Note: Unlike Java, Kotlin doesn’t require a new
keyword to initialize the constructor of a class.
String Equality
There are two types of equality checkers.
- Referential Equality: Checks if the pointers for two objects are the same.
===
operator is used. - Structural Equality : Checks if the contents of both the objects are equal.
==
is used.
Following code snippet demonstrates the above checkers.
var a = "Hello"
var b = "Hello again"
var c = "Hello"
var d1 = "Hel"
var d2 ="lo"
var d = d1 + d2
println(a===c) // true since a and c objects point to the same String in the StringPool
println(a==c) //true since contents are equal
println(a===b) //false
println(a==b) //false
println(a===d) //false since d is made up of two different Strings. Hence a and d point to different set of strings
println(a==d) //true since the contents are equal
Note: The negation of === and == are !=== and !== respectively.
This brings an end to kotlin string tutorial.