Kotlin String Template And String With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Kotlin String is represented by the data type String.

How to declare and define kotlin string variable

Format to declare a string in kotlin is as below –

var name: String

You can define a string in kotlin by assigning a value to it. For above example, we can do it as below –

var name: String
name = "Tutorialwing"

Here, last line assigns a string value “Tutorialwing” to variable name.

You can combine the two statement in one statement. This way we declare and define a string variable in same statement. We can do it as below –

var name: String = "Tutorialwing"

Here, we are declaring and defining a string variable in same statement in kotlin. Mentioning data type String is optional. If we do not mention the data type of the variable, then data type of variable is same as data type of the value being assigned to it. Since “Tutorialwing” value has data type String, type of variable name is also String.

We can declare and define the variable as below too –

var name = "Tutorialwing"

This example and above it have same meaning.

1. Guess the output of below program –

fun main(args: Array<String>) {
   var name = "Tutorialwing"
   print(name)
}

– Strings are immutable. You can not change a string value.

– Elements of String are characters. You can access it using indexing operation. For example, Character at ith position in a string S can be accessed by S[i – 1] . It is i – 1 because index starts from 0 .

fun main(args: Array<String>) {
   var name = "Tutorialwing"
   print(name[3]);
}

– You can concatenate Kotlin string values using + operator. You can concatenate string values with other data types as well. This is valid only if first value in the expression is of String type.

Let’s take an example,

fun main(args: Array<String>) {
    print("Tutorialwing " + 5);
}

Output of the above program will be Tutoralwing 5

1. Guess the output of the below program –

fun main(args: Array<String>) {
    print(5 + "Tutorialwing");
}

Kotlin String Literals

Kotlin String Literals have two types –
A. Escaped String Literals
B. Raw String Literals

A. Escaped String – Escaped strings may have escape characters in them. For example –
var s = “Hello, Tutorialwing!\n”

Here, we have escape sequence \n in the string. So, this is an escaped string.

Note – An Escaped string is a very much like a java string.

Escaping is done in using backslash like java programming language.

1. Guess the output of below program

fun main(args: Array<String>) {
   print("Tutorialwing")
   print("Tutorialwing")
   print("Tutorialwing")
   print("Tutorialwing")
   print("Tutorialwing")
}

Now, With escape sequence \n, guess the output of below program –

fun main(args: Array<String>) {
   print("Tutorialwing \n")
   print("Tutorialwing \n")
   print("Tutorialwing \n")
   print("Tutorialwing \n")
   print("Tutorialwing")
}

Output of the above program will be –
Tutorialwing
Tutorialwing
Tutorialwing
Tutorialwing
Tutorialwing

Now, you would have got an idea why do we use escape sequence.

B. Raw String – Kotlin raw string is delimited by triple quote (“””) . It contains no escaping and can contain newlines and any other characters. For example,

val text = """
Hello
Tutorialwing
"""

Example –

fun main(args: Array<String>) {
   val text = """
   Hello
   Tutorialwing
   """
   print(text)
}

When you run the program, you will get output as below –


    Hello
    Tutorialwing

Notice the empty whitespace before Hello and after Tutorialwing words.

You can trim such whitespaces using trimMargin() function. For example,

fun main(args: Array<String>) {
   val text = """
   Hello
   Tutorialwing
   """.trimMargin()
   print(text)
}

When you run the program, you will get output as below –

    Hello
    Tutorialwing

Notice the whitespaces before Hello or Tutorialwing words. If you want to remove such whitespaces too, you need to use a margin prefix to remove whitespaces before it.

Using | as margin prefix, the above program would look like below –

fun main(args: Array<String>) {
   val text = """
   |Hello
   |Tutorialwing
   """.trimMargin()
   print(text)
}

Output of the above program will be –

Hello
Tutorialwing

This was the final output we expected earlier.

If you want to use another character as margin prefix, you will have to pass it as a parameter in trimMargin() function.

Let’s take an example to understand it clear by taking ? as margin prefix –

fun main(args: Array<String>) {
   val text = """
   ?Hello
   ?Tutorialwing
   """.trimMargin("?")
   print(text)
}

Output of the above program will be –

Hello
Tutorialwing

Notice that we are using ? as margin prefix by passing ? in trimMargin() function.

Kotlin String Templates

As the name suggests, String templates contain template expression(s) in it. This template expression is evaluated and concatenated into the string.

How to use template expression for kotlin string template?

Template expression starts with a $ sign in kotlin. It either consists a simple name or an arbitrary expressions.

Some template expressions with simple name –
$name, $count, $age, $gender etc.

Basically, it is an expression containing $ sign and variable name.

Example –

fun main(args: Array<String>) {
   val name = "Tutorialwing"
   print("Your name is $name")
}

When you run the above program, you will get output as below –
Your name is Tutorialwing

Some template expression with arbitrary expressions –
$name.length , ${‘$’}1010 etc.

Example –

fun main(args: Array<String>) {
   val name = "Tutorialwing"
   print("Your name has ${name.length} characters.")
}

When you run the program, you will get output as below –
Your name has 12 characters.

Note that we have used expression ${name.length} to get the character length of variable name.

1. Guess the output of below program.

fun main(args: Array<String>) {
   val name = "Tutorialwing"
   print("Character at 5th position is $name[4]")
}

Output of the above program is –
Character at 5th position is Tutorialwing[4]

Did not expect this output?

Go through previous example of arbitrary expression. Notice that there is an { } bracket with arbitrary expression. You need to enclose the expression within this bracket.

So, the corrected example is –

fun main(args: Array<String>) {
   val name = "Tutorialwing"
   print("Character at 5th position is ${name[4]}")
}

Now, when you run the above program, you will get output as below –
Character at 5th position is r

Kotlin String template with raw string

We have already seen how to use string template with escaped string. Now, we will see how to use string templates with raw string.

Like escaped string, string template in raw string starts with $ sign. For example

val price = """
${'$'}200
"""
fun main(args: Array<String>) {
   val price = """
${'$'}200
"""
   print(price)
}

When you run the program, you will get output as below –
$200

Exercises on Kotlin String template and String

1. Guess the output of below program

fun main(args: Array<String>) {
   var name = "Tutorialwing"
   name = 10
   print(name)
}

2. Guess the output of below program

fun main(args: Array<String>) {
   val name = "Tutorialwing"
   name = "Rahul"
   print(name)
}

3. Guess the output of below program

fun main(args: Array<String>) {
   var name = "Tutorialwing"
   name = "Rah"
   print("name has ${name.length} characters")
}

4. Guess the output of below program

fun main(args: Array<String>) {
   val price = """
${'$'}${"200"}
"""
   print(price)
}

5. Guess the output of below program

fun main(args: Array<String>) {
   val price = """
       |${'$'}${"200"}
""".trimMargin()
   print(price)
}

That’s end of tutorial on Kotlin String and String Template.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners