Skip to main content

How to format a string with placeholders in Kotlin

How to format a string with placeholders in Kotlin.

Here's a step-by-step tutorial on how to format a string with placeholders in Kotlin:

  1. Import the necessary package:\ To use string formatting in Kotlin, you need to import the java.util.Formatter package. Add the following line at the top of your Kotlin file:

    import java.util.Formatter
  2. Create a format string:\ Start by creating a format string with placeholders. Placeholders are denoted using % followed by a formatting specifier. For example, %s is used for strings, %d for integers, %f for floating-point numbers, etc. Here's an example format string:

    val formatString = "Hello, %s! You are %d years old."
  3. Create a formatter object:\ Initialize a Formatter object by passing the format string to its constructor:

    val formatter = Formatter()
  4. Format the string:\ Use the format() method of the Formatter class to substitute the placeholders with actual values. Pass the formatted string and the values as arguments to the format() method:

    val name = "John"
    val age = 30
    val formattedString = formatter.format(formatString, name, age).toString()

    In this example, the %s placeholder is replaced by the value of name, and the %d placeholder is replaced by the value of age.

  5. Print or use the formatted string:\ You can now use the formattedString variable to print or use the formatted string as needed. Here's an example of printing the formatted string:

    println(formattedString)

    Output:

   Hello, John! You are 30 years old.
  1. Close the formatter:\ After you are done using the formatter, it is good practice to close it to release any system resources it may be holding:

    formatter.close()

    Closing the formatter is especially important if you are working with a large number of formatted strings.

That's it! You have successfully formatted a string with placeholders in Kotlin. Remember to import the java.util.Formatter package, create a format string with placeholders, create a formatter object, format the string with values, and finally, close the formatter when you're done.

Here's the complete code example:

import java.util.Formatter

fun main() {
val formatString = "Hello, %s! You are %d years old."
val formatter = Formatter()
val name = "John"
val age = 30
val formattedString = formatter.format(formatString, name, age).toString()
println(formattedString)
formatter.close()
}

Output:

Hello, John! You are 30 years old.

Feel free to modify the format string and placeholders based on your specific requirements.