Kotlin String

The string is a sequence of characters enclosed within double and triple quotes. It is immutable means you cannot change the individual character of a string. It is represented by the type String.

6. Kotlin String 6.1 Get String Index 6.2 String Iteration 6.3 String Templates 6.4 String Equality 6.5 Get Sub String 6.6 Kotlin Raw String 6.7 Kotlin String Plus


Get String Index

In Kotlin, index operator is used to access an element of a string.

fun main(args : Array<String>) 
	var a = "Hello, World"
	println(a[0])
	println(a[3])
	println(a[5])
}
Output
H
l
,

String Iteration

We can iterate over a string using for loop.

fun main(args : Array<String>) 
	var str = """This is envisioned and developed to meet basic and free courses to learn, succeed and belong."""
	for (s in str) {
		println(s)
	}
}
Output
H
e
l
l
o
 
W
o
r
l
d
.




String Templates

In Kotlin, string can contain template expressions, means we can evaluate the code string. This string expression starts with dollar sign.

Example of String

var i = 5
println("i = $i")

The string template arbitrary expression is written in curly braces.

fun main(args : Array<String>) 
	var i = "etutorialspoint"
	println("$i.length is ${i.length}")
}
Output
etutorialspoint.length is 15

If there is a requirement to include a literal dollar sign in a string, a backslash is used.

val str = "\$str" // evaluates to "$str"

String Equality

The string structure equality is compared with double equality operator.

fun main(args : Array<String>) 
	val str1 = "Welcome, Somya!"
	val str2 = "Welcome," + " Somya!"
	println(str1 == str2) // output: true
}

Get Sub String

Kotlin provides subSequence() function to return a substring between the specified start and end index.

Syntax

subSequence(startIndex, endIndex)

Example

fun main(args : Array<String>) 
	val str = "Welcome, Somya!"
	println(str.subSequence(0,6)) // Output : Welcome
}

Kotlin Raw String

The raw string is multiline string placed inside triple quotes. There is no need to escape characters in raw string.

Example

fun main(args : Array<String>) 
    val str = """Welcome, Somya!
    you are learning
    kotlin programming language"""
	println(str)
}
Output
Welcome, Somya!
    you are learning
    kotlin programming language

Kotlin String Plus

In kotlin, plus() function returns a new string by concatenating strings.

Example

fun main(args : Array<String>) 
	val str = "Welcome, Somya!"
	var str1 = "How are you!"
	var result: String
	result = str.plus(str1)
	println($result)
}
Output
Welcome, Somya! How are you!