Table of contents
1.
Introduction
2.
Properties and Functions in String
2.1.
Length of a String
2.2.
Converting String alphabets in lower and upper case
2.3.
get index of a Sub-String in the given String
2.4.
Comparing two strings are equal or not
2.5.
get char/element at a particular index
2.6.
Finding subSequence in String
3.
String Literals
3.1.
1. Escaped String: 
3.2.
2. Raw String(or multi-line String):
4.
String Equality
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Strings And Their Associated Methods

Author Akshit Pant
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In simple terms, Strings are an array of characters and are used for storing text.

The content of the String is written within the double quotes("…content.."). We know that Kotlin was introduced after being inspired by existing programming languages like Java. As a result, Kotlin strings are mainly similar to Java strings with some newly added functionalities. So, Kotlin Strings are immutable, i.e., we can not change the length and elements of the String after their creation.

If you are curious to know the difference between Java and Kotlin, then here is the link.

If you are new to Kotlin, then here is your guide.

Syntax to declare a string in Kotlin:

fun main(){
var var_name : String = "Coding Ninjas"
println(var_name)
}

Also, note that we do not need to mention that var_name is a string 

Reason: Kotlin is smart enough to understand that the var_name above is a string type because it contains double-quotes.

fun main(){
var var_name = "Hello, Ninjas"
println(var_name)
}

How to access elements of a String?

Every char written within the String is called its element, and every element can be accessed easily using its index. 

Elements are stored in the String with indexes ranging from (0) to (range-1 or String.length -1).

Ways-

Using Index: Return the char at the specified index.

Using get Function: returns char at the specified index. In this case, the index is passed as an argument in the get function/method. 

Using Iterative approach: using loops over the string to access its characters.

Example-

Input:

fun main(){
// Simply returning the char at the specified index by accessing string elements one after another
    var str = "Coding"
    println(str[0])
    println(str[1])
    println(str[2])
    println(str[3])
    println(str[4])
    println(str[5])
    }

Output:

C
o
d
i
n
g

Input:

fun main(){
// using iterative approach of for loop
    var str2 = "NINJAS"
    for(j in str2.indices){
        print(str2[j]+" ")
    }
    }

Output:

NINJAS

String access using String template-

String templates always start with a $(dollar sign) and then are followed either by a var(variable) name or an arbitrary expression in {}.

Example-

 Input:

fun main(){
var x = 10
 println("Printing the value of our variable x: $x") 
 }

Output:

Printing the value of our variable x: 10

 

Input:

fun main(){
// string using  arbitrary expression in {}
   val str = "Coding Ninjas Kotlin Blog"
   println("$str is a string of length ${str.length}")
   }

 Output:

Coding Ninjas Kotlin Blog is a string of length 25

Properties and Functions in String

Some of the important properties and functions in String are shown below:

Length of a String

 In Kotlin, the length of a string can be found using the String.length property. String length is basically the count of the total number of elements in that String.

Let us understand this with an example that if CodingIsTheKeyToCP is a string then the total number of elements/char in it are-

Input:

fun main(){
var s = "CodingIsTheKeyTOCP"
println(s.length)
}

Output:

18

Converting String alphabets in lower and upper case

It can be done simply by using string.toUpperCase and string.toLowerCase functions to convert strings in uppercase and lowercase respectively.

Let us understand it with an example of the string “Coding Ninjas”.

Input:

fun main(){
var s = "Coding Ninjas"
println(s)    
println(s.toUpperCase())   // converts s in upper case alphabets
println(s.toLowerCase())   // converts s in lower case alphabets
}

Output:

Coding Ninjas
CODING NINJAS
coding ninjas   

get index of a Sub-String in the given String

Let's say we want to see the index of Ninjas(which is a String) from another String "Coding Ninjas also provide Interview Prep Courses!" String.

We can do so using var_name.indexOf("String").

  Input:  

fun main(){
var txt = "Coding Ninjas also provide Interview Prep Courses!"
             println(txt.indexOf("Ninjas"))  
             }

Output:

7

Here the indexof() Function returns the index(or position) of the first occurred specified String. 

NOTE: Whitespace between words also takes an index.

Comparing two strings are equal or not

 So the compareTo(str ) function compares two strings and returns 0 if both are the same.

Input:

fun main(){
var s1 = "Hello Ninjas"
var s2 = "Hello Ninjas"
println(s1.compareTo(s2))
}

Output:

0

Otherwise, It will never return 0.

Here is an example -

Input:

fun main(){
var s1 = "Hello Ninjas"
var s2 = "Hello Coders"
println(s1.compareTo(s2))
}

Output:

11

get char/element at a particular index

It simply returns the char at a particular index.

Input:

fun main(){
var s = "CodingNinjas"  
print(s.get(3)) 
}

Output:

i

Finding subSequence in String

subSequence(starting index, end index): It returns a substring that starts from the starting index and ends at the end index-1.

Input: 

fun main(){
var s = "CodingNinjas"  
print(s.subSequence(1, 4))
}

Output:

odi

String Literals

  1. Escaped String
  2. Raw String

1. Escaped String: 

The Escaped String is declared with "....."(double quotes), and it can contain escape characters like /n.

fun main(){
val str = "Coding \n is \n amazing"                       // escape string
  println(str)
  }

Output:

Coding 
 is 
 amazing

2. Raw String(or multi-line String):

 It is placed/written inside the triple quotes, i.e., ("""...""") and it can never have escape characters. Since it provides the facility for writing the String into multiple lines, it is called a multi-line string. 

fun main(){
       var s = """My                           // raw string(multi line string)
        |name
        |is
        |AkshitPant
    """.trimMargin()
    println(s)
    }

 

Output:

My
name
is
AkshitPant

 Here, you might be wondering about the use of .trimMargin().

The point is that while using raw String, with every new line, it generates a | as margin prefix.
So if we do not use it, then the output looks this way—

Input:

fun main(){
var s = """My
        |name
        |is
        |AkshitPant
    """
    println(s)
    }

Output:

My
        |name
        |is
        |AkshitPant

String Equality

 Kotlin allows you to compare instances of a particular type in two separate ways. This characteristic distinguishes Kotlin from other programming languages.

There are two sorts of equality:

  1. Structural Equality:
  2.  The == operator and its inverse! Check structural equality. By default, the expression that contains x==y kind of equation is translated into a call of equivalent .equals() Function.
  3. Referential Equality:
  4.  The === and inverse!== operators in Kotlin are used to check for referential equality. When both the instances of a type point to the same memory address/location, it returns true. The === check is transformed to == check, and the!== check is converted to!= check when used on types that are turned into primitives at runtime.

FAQs

  1. How are Kotlin strings different from java strings?
    Since Kotlin is an extension of Java for mobile application development, Kotlin strings are mainly similar to Java strings with some newly added functionalities.
     
  2. Is Kotlin String mutable?
    Having similarities with the Java programming language, Kotlin Strings are immutable, i.e., we can not change the length and elements of the String after their creation.
     
  3. How can we create an empty string in Kotlin?
    For creating an empty string in Kotlin, we need to create an instance of String class, like  
     var var_name = String ()
     
  4. What range does subSequence(start, end) covers when the range goes as start = 0 and end = 5?
    subSequence function print range goes from start to end-1. So, when the start is 0 and the end index is 5, coverage will be 0 to the 4th index.
     
  5. What is the difference between == and === operator?
    The == and it’s inverse != operator checks Structural Equality, whereas === and it’s inverse !== operator checks Referential Equality.

Key Takeaways

Cheers if you reached here!! 

The purpose of this article was to introduce you to the Kotlin Strings and give some basic idea about how to initialize and use them with their properties and functionalities.

If you want to set up your Kotlin environment for programming, then here is the help.

Recommended problems -

 

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. Till then, Happy Learning!

Live masterclass