String based Kotlin interview questions and answers

How does string interpolation work in Kotlin? Explain with a code snippet?

String interpolation is used to evaluate string templates.
We use the symbol $ to add variables inside a string.


val name = "Journaldev.com"
val desc = "$name now has Kotlin Interview Questions too. ${name.length}"

Using {} we can compute an expression too

How to compare two strings in Kotlin?

Compares string in Kotlin are possible in the following ways:

  1. Using “==” operator:

You can use ah operator for comparison of two string. In Kotlin == operator is used.

  1. Using compareTo() extension function

Syntax of compareTo() function is given below :

fun String.compareTo(
      other: String,
      ignoreCase: Boolean = false
): Int

Another code example

fun main(args: Array & lt; String & gt;) {

    val x: String = "Kotlin is  simple"
    val y: String = "Kotlin language is" + " easy"
    if (x == y) {
          println(" x and y are similar.")
    } else {
          println(" x and y are not similar.")
    }
}
Mention the type of strings present in Kotlin?

Basically, strings refer to a collection of various characters altogether. There are two types of strings present in Kotlin which are-

  • Raw strings
  • Escaped strings

Under these strings, templates can also be evaluated easily and this evaluation is known by term as string template interpolation

How can you check if two Strings are equivalent esteemed?
 
We can cheek if tow stings are equivalent esteemed using of Using == (double equal to) operator.


How to correctly concatenate a String in Kotlin? ☆☆

Answer: In Kotlin, you can concatenate

  1. using string interpolation / templates
val a = "Hello"
val b = "World"
val c = "$a $b"
  1. using the + / plus() operator
val a = "Hello"
val b = "World" 
val c = a + b   // same as calling operator function a.plus(b)
val c = a.plus(b)

print(c)
  1. using the StringBuilder
val a = "Hello"
val b = "World"

val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()

print(c)

Aaaaass

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Null safety based Kotlin interview questions and answers

CustomView based Android interview questions and answers