An array of characters is called a string. Kotlin strings are mostly similar to Java strings but have some newly added functionalities. Kotlin strings are also immutable in nature means we can not change the elements and length of the String.
The String class in Kotlin is defined as:
class String : Comparable<String>, CharSequence
To declare a string in Kotlin, we need to use double quotes(” “), single quotes are not allowed to define Strings.
Syntax:
var variable_name = "Hello, Geeks"
or
var variable_name : String = "GeeksforGeeks"
Creating an empty String:
To create an empty string in Kotlin, we need to create an instance of the String class.
var variable_name = String()
String Elements and Templates
String Element
The character, digit or any other symbol present in string is called as element of a String. We can easily access the element of the string using string[index]. Elements store in a string from index 0 to (string.length – 1).
There are three ways in which you can access string elements in Kotlin
- Using index: Returns the character at specified index.
- Using get function: Returns the character at specified index passed as argument to get function.
- Iterating over the String: Using loops to access the characters in the String.
Kotlin program to access the elements of a string
Kotlin
fun main(args: Array<String>){
var str = "Hello"
println(str[0])
println(str[1])
println(str[2])
println(str[3])
println(str[4])
var str2 = "Geeks"
for(i in str2.indices){
print(str2[i]+" ")
}
}
|
Output:
H
e
l
l
o
G e e k s
String Template
String template expression is a piece of code which is evaluated and its result is returned into string. Both string types (escaped and raw string) contain template expressions. String templates starts with a dollar sign $ which consists either a variable name or an arbitrary expression in curly braces.
Kotlin
fun main(args: Array<String>) {
var n = 10
println("The value of n is $n")
val str = "Geeks"
println("$str is a string which length is ${str.length}")
}
|
Output:
The value of n is 10
Geeks is a string which length is 5
Some important properties and functions in String
Length: Returns the length of the String.
var s =" String"
println(s.length)
get(index): Returns the character at that particular index.
s.get(3) // Output: - i
subSequence(start, end):Returns a substring starting from start and ending at end but excluding end.
s.subSequence(1, 4) // Output: - tri
str.compareTo(string): Returns 0 if str == string.
Kotlin program of using the above properties and functions
Kotlin
fun main(args: Array<String>) {
var g = "GeeksForGeeks"
var e = "Geeks"
println(g.length)
println(g.get(4))
println(g.subSequence(0, 5))
println(g.compareTo(e))
}
|
Output:
13
s
Geeks
8
String Literals
There are two types of string literals in Kotlin –
- Escaped String
- Raw String
Escaped String
Escaped string is declared with double quotes (“….”) and it may contain escape characters like \n, \t etc.
Kotlin program of escaped string:
Kotlin
fun main(args: Array<String>) {
val str = "World \n is \n amazing"
println(str)
}
|
Output:
World
is
amazing
Raw String – Multi-line String
Raw string is placed inside the triple quotes (“””….”””) and it does not have escape characters. It provides the facility of writing the string into multiple lines so it is also called multi-line string.
Kotlin program of raw string:
Kotlin
fun main(args: Array<String>) {
var str = """My
|name
|is
|Yash
""".trimMargin()
println(str)
}
|
Output:
My
name
is
Yash
Escape Characters – Some of the escape characters are:
- \” : for double quote
- \r : for carriage return
- \n : for newline
- \’ : for single quote
- \\ : for backslash
- \t : for tab
- \b : for backspace
String Equality
Kotlin provides an additional feature of comparing the instances of a particular type in two different ways. This feature makes Kotlin different than the other programming languages.
The two types of equality are
- Structural Equality
- Referential Equality
Structural Equality
Structural equality is checked through the == operator and its inverse != operator. By default, the expression containing x==y is translated into the call of equals() function for that type.
Referential Equality
The referential equality in Kotlin is checked through the === operator and its inverse !== operator. This equality returns true only if both the instances of a type point to the same location in memory. When used on types that are converted into primitives type at runtime, the === check is converted into == check and !== check is converted into != check.
Kotlin program to demonstrate the structural and referential equality
Kotlin
fun main(args: Array<String>) {
var x = "GeeksForGeeks"
var y = "GeeksForGeeks"
var z = "Geeks"
println(x===y)
println(x==z)
println(x===z)
}
|
Output:
true
false
false
Looking to become an expert in Android App Development? Whether you're a student or a professional aiming to advance your career in mobile app development, our course, "Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the perfect fit for you. Gain hands-on experience with Kotlin, the modern language preferred by Android developers worldwide. This course will guide you through the essentials of Android app development, from the basics to advanced techniques, using practical projects and real-world scenarios. Ideal for beginners and those looking to enhance their existing skills, this course will equip you with the expertise needed to build high-quality, robust Android applications. Ready to master Android development? Enroll now and elevate your career to new heights!
Similar Reads
Subscript and Superscript a String in Android with Kotlin
In science, a scientific expression defining a context is a combination of a finite number of symbols according to the rules of the context. So in a basic sense, such expressions are formed by various writing styles or scripts such as lower case, upper case, symbols, numbers, subscripts, superscripts, etc. So in this article, we will show you how y
2 min read
Kotlin | Language for Android, now Official by Google
Kotlin is a new Open-Source programming language from JetBrains. It first appeared in 2011 when JetBrains unveiled their project named "Kotlin". Basically like Java, C and C++ â Kotlin is also a "statically typed programming language" (languages in which variables need not be defined before they are used). Static typing does not mean that we have t
5 min read
Why Kotlin will replace Java for Android App Development
We have a new member in our programming languages family and itâs none other than Kotlin. In Google I/O â17, they have finally announced that for android the official first class support will be given to the Kotlin. We can almost say that Kotlin is officially in for android development and java is almost getting pushed out of the frame. While java
4 min read
Introduction to Kotlin
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is object-oriented language, and a "better language" than Java, but still be fully interoperable wi
4 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
2 min read
Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example + and - are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. Arithmetic operatorRelation operatorAssignment operatorUnary operatorLogical operatorBitwise operator Arithmetic Operators -
3 min read
Kotlin if-else expression
Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If the condition is true then it enters into the condi
4 min read
Kotlin when expression
In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to end of the when block and executes the code next
6 min read
Kotlin for loop
In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of for loop in Kotlin: for(item in collection) { // code to execute } In Kotlin
4 min read
Kotlin while loop
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines. While loop - It consists of a block of code and a condition. First
2 min read