'How to append 2 strings in Kotlin?

I am trying to concatenate 2 String but not sure how to go about it.

this is my code:

 val word = R.string.word

and i'm trying to append it with "$currentPage/5" inside the setText("$currentPage/5") i tried to make it in this way setText("$word $currentPage/5") and this way setText("${R.string.value} $currentPage/5") and it did not work , it only shows me numbers not the text



Solution 1:[1]

In Kotlin, the concatenation of string can be done by **interpolation/templates**.

val a = "Its"
val b = "Kotlin!"
val c = "$a $b"

The output will be Its Kotlin!

Or we can alson do concatenate using the **+ / plus() operator**:

val a = "String"

val b = "Concatenate"

val c = a + b   

val d =a.plus(b)

print(c)
The output will be: StringConcatenate

print(d)
The output will be: StringConcatenate

Or you can concatenate using the StringBuilder which is a normal way to do that.

Solution 2:[2]

To concatenate two string, we could do

val concatenatedWord = "${resources.getString(R.string.value)}: ${number/3}."

If R.string.value was "The result" and number was 15, value of concatenatedWord will be "The result: 5." Or we could also concatenate using the + operator or using StringBuilder.

But if you do textView.text = "${resources.getString(R.string.value)}: ${number/3}."
AS will warn "Do not concatenate text displayed with setText." so, in the case of setting concatenated text in textview, consider using

String.format("%s: %d.", resources.getString(R.string.value): number/3)

Solution 3:[3]

As a future resource and answer why the accepted answer works:-

String Templates:-

Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string.

How to implement these?

A template expression should start with a dollar sign ($) and consists of either a simple name:

  • when the expression is a simple variable.

      val i = 10
      println("i = $i") // prints "i = 10"
    
  • or else arbitrary expression in curly braces:

      val s = "abc"
      println("$s.length is ${s.length}") // prints "abc.length is 3"
    

Note :- Templates are supported both inside raw strings and inside escaped strings.

Solution 4:[4]

val nameOfAnimal = "fish"
val speciesClass =  "is an Aquatic Vertebrate"    
     
     println(nameOfAnimal.plus(speciesClass))
     println(nameOfAnimal+speciesClass)
     println("$nameOfAnimal   $speciesClass")

Results:

fishis an Aquatic Vertebrate
fishis an Aquatic Vertebrate
fish   is an Aquatic Vertebrate

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhinandan Chada
Solution 2 anoo_radha
Solution 3 Kaveri
Solution 4 Faakhir