Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




KOTLIN - STRINGS


A String is a collection of letters/alphabets. It can be a word or a sentence.


The 'Data Type' for String is 'string'.


Declaring a String with Double Quotes ("")


When Kotlin finds data inside Double Quotes (""). It creates a String type variable for that value.


var x = "Hello World"

Example :



fun main() {
    var x = "Hello World"
    println(x)
}


Output :



 Hello World

And that's all! You have a String in place.


Well! There are other ways using which you can create a string.


Declaring a String with string data type


Example :



fun main() {   
    var x: String = "Hello World"
    println(x)
}


Output :



 Hello World

So, in the above code, we have declared a variable 'x' of 'String' type.


var x: String = "Hello World"

So that it would not accept any other values other than a String.


Also one more advantage of declaring using a 'String' type is that you can assign the value to the String variable later.


Let us understand with the below code.


Example :



fun main() {   
    var x: String 
            
    x = "Hello World"
    println(x)
}	


Output :



 Hello World

Just note that we have not initialised the variable 'x'. We have just declared it.


var x: String

So that an empty variable 'x' would be created that would only hold a String.


java_Collections

Then in the next line, we have assigned the value 'Hello World' to the variable 'x'.


x = "Hello World"

java_Collections

Well! We have declared a String type variable and assigned it later.


But the below code won't work, if we do not specify a data type.


Example :



fun main() {   
    var x 
            
    x = "Hello World"
    println(x)
}	


Output :



 This variable must either have a type annotation or be initialized

So far, we have seen, how to declare a String type variable in one line.


Now, what if, we want a paragraph, separated by lines, to be assigned to a variable.


i.e. Let's say, you want to assign the below paragraph to a variable.


"In a huge pond,
there lived many fish.
They were arrogant
And never listened to anyone."

In such cases, you can use three double quotes ("""""").


Declaring a multiline String with three double quotes ("""""")


Declaring a multiline String with three double quotes ("""""") :


Example :



fun main() {

var str = """In a huge pond,
there lived many fish.
They were arrogant
And never listened to anyone."""
        
println(str)
        
}	


Output :



 In a huge pond,
 there lived many fish.
 They were arrogant
 And never listened to anyone.

Accessing the characters of a String


Example :



fun main() {

    var x = "Hello"  
    var y = x[1]
            
    println(y)    
}


Output :



 e

So, we have a string 'Hello',


var x = "Hello"

And we have assigned 'Hello' to a variable 'x'.


java_Collections

Let us elaborate more, on how the String 'Hello' is stored in the variable 'x'.


java_Collections

So, just for the sake of understanding, you can assume the variable 'x' is divided into '5' parts to store 'Hello'.


Now, if you check from the front, the count starts from '0' and ends with '4'.


So, if we look at the next line in the code,


y = x[1]

We are trying to access the 2nd location,


java_Collections

So, 'x[1]' is referring to the 2nd location where 'e' is stored.


y = x[1]

And we have assigned 'e' to the variable 'y'.


java_Collections

Note : The square brackets '[]' are used with the string type variable to get the variable at that position(i.e. x[1] refers to the 2nd location that contains 'e').

Now, if you look at the print statement,


println(y)

The value of 'y' is printed as output.


Output :



 e

In the earlier examples, we have seen the '+' sign. And as we know, '+' is used for addition of two numbers.


Well! In Kotlin, '+' can be used to join two Strings as well.


Concatenation of Strings


Say, we have two Strings, 'Hello' and 'World'. And we want to join/concatenate them into one String, 'HelloWorld'.


Let us solve it with the below example.


Example :



fun main() {   
    var x = "Hello"
    var y = "World"
    var z = x + y
    println(z)
}


Output :



 HelloWorld

So, we have stored the String 'Hello' in 'x'.


x = "Hello"

And, stored the String 'World' in 'y'.


y = "World"

And used the '+' operator to join/concatenate 'Hello' and 'World'.


z = x + y

And store the concatenated value in 'z'.


java_Collections

So, '+' is not just used to add two numbers but '+' is also used to join/concatenate two Strings.


But we cannot use the '+' operator to join/concatenate a number and a String.


i.e. The below code will result into an error.


Example :



fun main() {   
    var x = 5
    var y = "World"
    var z = x + y
    println(z)
}


Output :



 None of the following functions can be called with the arguments supplied:
 public final operator fun plus(other: Byte): Int defined in kotlin.Int
 public final operator fun plus(other: Double): Double defined in kotlin.Int
 public final operator fun plus(other: Float): Float defined in kotlin.Int
 public final operator fun plus(other: Int): Int defined in kotlin.Int
 public final operator fun plus(other: Long): Long defined in kotlin.Int
 public final operator fun plus(other: Short): Int defined in kotlin.Int

And as said it ended up with an error.


Now, what if, you wish to repeat a string a few number of times.


Repetition of a String using Repeat() Function


To repeat a String a few number of times, Kotlin provides us with a Function called 'Repeat()' that repeats a string a few number of times.


Note : Function is a topic that will be discussed in a separate tutorial. For now, you can consider, a Function is something that is dedicated to do some specific work. Just like the work of Repeat() Function is to repeat a string a few times.

Let us see the below example.


Example :



fun main() {   
   	
    var x = "Hello"
    var y = x.repeat(3)
            
    println(y)
}


Output :



 HelloHelloHello

So, if you see the output. The statement,


var y = x.repeat(3)

Repeats the String 'Hello' three times.


y = strings.Repeat(x,3)

java_Collections

Next, let us see how to Iterate through the values of a String.


Iterate a String using for range loop


Example :



fun main() {
    var x = "Hello"
    for (i in x) {
        println(i)
    }
}


Output :



 H
 e
 l
 l
 o

So, in each Iteration of 'for loop',


for (i in x)

The values are taken from the variable 'x', one by one and put in the variable 'i'.


And values are printed at each Iteration.


println(i)

Now, let us look at a scenario, where you need to find out, if a particular letter or a chunk of letters is present in the string or not.


Checking if a substring is present in a String or not using Contains() function


Let us check, if the substring 'el' is present in the String 'Hello' or not.


To achieve it, Kotlin provides a function called 'Contains()' that checks if a substring is present in a string or not.


Example :



fun main() {
    var x = "Hello"
    if (x.contains("el")) {
        println("The sub-string, el is present in the String, Hello")
    } else {
        println("The sub-string, el is not present in the String, Hello")
    }
}


Output :



 The sub-string, el is present in the String, Hello

So, to check if the substring 'el' is present in the String 'Hello', we have used the 'contains()'function with 'if' statement.


if (x.contains("el"))

Note : The below topic 'String Templates' is already explained in the tutorial 'Input & Output'.

String Templates


Say, you have stored a number in a variable and you want to insert it in the middle of a String.


i.e. Say, you have two numbers '3' and '4' and you have added them and want to display the result in the following way,


The added result of 3 and 4 is 7

Well! We can achieve it using String formatting.


String Template Operator '$'


Let us rewrite the above example using the String Template Operator '$'.


Example :



fun main() {

    var x = 3
    var y = 4
    var z = x + y
    println("The added value of $x and $y is $z")
}


Output :



 The added value of 3 and 4 is 7

Now, if you look at the output,


The added value of 3 and 4 is 7

The variables of 'x', 'y' and 'z' is replaced with the actual values i.e. '3', '4' and '7'.


java_Collections

String Formatting


We can also achieve the above using String formatting.


String Formatting Operator '%' and format() function


Let us rewrite the above example using the String Formatting Operator '%'.


Example :



fun main() {

    var x = 3
    var y = 4
    var z = x + y
    var result = "The added value of %d and %d is %d"
    println(result.format(x, y, z))
}


Output :



 The added value of 3 and 4 is 7

Now, if you look at the output,


The added value of 3 and 4 is 7

You can see that '%d' is replaced with the actual values of the variables.


println(result.format(x, y, z))

Similarly, we can use other placeholders for all types of data.


Below is the List :





Type Description
d, i, u Decimal Number
x, X Hexadecimal Number
o Octal Number
f, F Floating Point Number
e, E Exponential Number
g, G Floating point/Exponential
c Single character
s, r, a String

How to find the length of a String?


length


'length' keyword is used to return the length of a String.


Example :



fun main() {

    var x = "Hello"
    println("The length of the String is : "+x.length)
}


Output :



 The length of the String is : 5

Next, let us look at the Functions provided by Kotlin to handle Strings more effectively.