Kotlin String

String form a very important part in terms of input and output. All the input and output processing (including file I/O, Stream I/O) for kotlin as similar to Java is done in the form of Strings. Now let’s recall the Java’s main function.

public static void main(String [] args){	
	//Here, if you refer args or run time arguments are again taken in the form of Strings.
}


Similar, to Java the main() function to Kotlin’s main() function:

fun main(args: Array<String>) {
    		println("Hello World!")
}

As explained, the default input type is “String”. Now, lets discuss what are Strings.

Kotlin String

String is an array of characters. Similar to Java strings, Kotlin Strings showcases more or less the same similarity except with some new add-ons. Moreover strings in Kotlin are also immutable just as Java Strings means we cannot change or modify its state once it is initialized. Let’s see and understand how we can define Strings in Kotlin.

Syntax:

String is implemented in Kotlin using the String class.

var var_name: String = "Hello"

or

var var_name = "Hello"

When creating String in Kotlin, below are rules to be kept in mind:

  1. We need to use double quotes to declare the String in Kotlin.
  2. If we need to create an empty String, we need to instantiate the String Class first. Unlike Java, Kotlin doesn’t require a new keyword to create an instance of String Class. Let us check with an example:
var var_name = String()

Let’s create String in Kotlin and see its working:

fun main() {
    var a : String = "Hello, world!"
    
    var s = "Hello World"
    println("String a :"+a)
    println("String s :"+s)
}

Output:

String a :Hello, world!
String s :Hello World

Functions and Properties of String Class

As String is a class in Kotlin, it is bound to have certain functions and Properties (state and behavior) as we refer. Let’s see all these functions & properties which make our coding easier:

Length Property:

Using the dot operator of the String, it returns the number of characters present in the string.

fun main() {
    var a : String = "Hello, world!”   
    println("Length Of String a :"+a.length)
}

Output:

Length Of String a :13

Get Function:

The get function is used when we want a character specified at a particular index.

fun main() {
    var a : String = "Hello, world!"    
    println("Char at Index 0 is:"+a.get(0))
}

Output:

Char at Index 0 is: H

Let’s see the output when we are trying to print the character which is not present.

fun main() {
    var a : String = "Hello, world!"     
    println("Char at Index 0 is: "+a.get(15))
}

Output:

Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 15
at java.lang.String.charAt (String.java:658)
at FileKt.main (File.kt:9)
at FileKt.main (File.kt:-1)

StringIndexOutOfBoundsException: When we try to get the index of a String which is not present in the String, then the system throws the Exception.

Sub Sequence Function:

Similar to the substring function in Java, we have a function in Kotlin which provides the substring from a particular String. This method excluding the endIndex character.

Arguments of the Method:

  • Start Index: Integer, This is the startIndex, required for the start of Sub Sequence.
  • End Index: Integer, This is the endIndex, required for the end of Sub Sequence.

Let’s see an example of the subSequence:

fun main() {
    var a : String = "Hello, world!”
    println("Char at Index 0 is: "+a.subSequence(0,5))
}

Output:

Char at Index 0 is: Hello

Compare to Function:

If one String is equal to another string, then while comparing it will return 0. But if first string is less than another string, it will return a positive number.

Sr. No. Result Explanation
1 Positive Number The First String is less than the Another String
2 Negative Number The First String is greater than the Another String
3 Zero When the two Strings are Equal
fun main() {
    var a : String = "Hello, world!"
    var b : String = "Hello, world!"
    println("When the Strings are Same "+a.compareTo(b))
    a="Hello"
    println("When the Strings are Same "+a.compareTo(b))
    println("When the Strings are Same "+b.compareTo(a))   
}

Output:

When the Strings are Same 0
When the Strings are Same -8
When the Strings are Same 8

There’s another flavor of using compareTo function, by passing an argument for the Case. If we modify the above example to ignore the case while comparing the Strings.

/**
 * You can edit, run, and share this code. 
 * play.kotlinlang.org 
 */

fun main() {
    var a : String = "Hello, World!"
    var b : String = "Hello, world!"
    println("When the Strings are Same "+a.compareTo(b,true))
    println("When the Strings are Same "+a.compareTo(b,false))
    a="Hello"
    println("When the Strings are Same "+a.compareTo(b))
    println("When the Strings are Same "+b.compareTo(a))    
}

Output:

When the Strings are Same 0
When the Strings are Same -32
When the Strings are Same -8
When the Strings are Same 8

String Equality:

String Equality is an important feature which distinguishes Kotlin from other programming languages. It provides the feature to compare the instances of the particular type. There are two types of String Equality.

  1. Structural Equality
  2. Referential Equality

Let’s discuss these in detail:

Structural Equality: Structural Equality checks if the content of both the objects equal. We can check for structural equality (==).

Referential Equality: Referential Equality checks if the pointers of the two objects are equal. We can check for referential equality (===).

fun main() {
var str = "Hello"
var str1 = "Hello again"
var str2 = "Hello"
var str3 = "Hel"
var str4 ="lo"
var str5 = str3 + str4

println(str===str2) // true since str and str2 objects point to the same String in the StringPool
println(str==str2) //true since contents are equal
println(str===str1) //false
println(str==str1) //false
println(str===str5) //false since str5 is made up of two different Strings. Hence str and str5 point to different                            set of strings
println(str==str5) //true since the contents are equal
}

Output:

true
true
false
false
false
true

Index based String Access

As seen above, the String class in Kotlin provides index based access using the []. Let’s try to access the elements:

fun main() {
var str = "Hello World"
	for(element in str){
      		println(element)
  	}  
}

Output:

H
e
l
l
o

W
o
r
l
d

Based on the above reading we can conclude the three ways to access a String:

  • Using Index
  • Using get()
  • Iterating the String using a loop

There are times, when we wish to simply using a string variable inside a print statement. Yes, kotlin supports that using String Template.

String Template

The result of String Template is returned within the string. When we need to concatenate, String can contain expression which is followed by a $ symbol.

fun main() {
	var str = "Kotlin Blog"
   	print("Hello $str and the length is ${str.length}. ")
}

Output:

Hello Kotlin Blog and the length is 11.

We can insert variables and expressions in a string .Also when we need to use $ symbol for any purpose, we need to escape the character.

Escape Characters in Kotlin

We often prefer to use the escape characters that when used with ‘\’ backslash behave differently.

  • \n newline.
  • \r carriage return.
  • \t tab.
  • \b backspace
  • \” double quote
  • \’ single quote
  • \\ backslash

The next comes the concept of String Literals.

String Literals

Kotlin supports two different types of literals:

1) Escaped String

2) Raw String

The Escaped Literal:

Similar to strings, escaped strings is also declared with double quptes (“…”) and it can contain escape characters such as /t,/n etc.

Example:

fun main() {
	val str = "Kotlin \n is\nfun\t to \n learn."    
    print(str)
}

Output:

Kotlin 
 is
fun	 to 
 learn.

That was all about Strings, there are many other options amongst above which can be used interchangeably. Such flexibility of Strings makes them an optiomal choice to be used when working on Input/Output.

Leave a Comment

Your email address will not be published. Required fields are marked *