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:
Import the necessary package:\ To use string formatting in Kotlin, you need to import the
java.util.Formatterpackage. Add the following line at the top of your Kotlin file:import java.util.FormatterCreate a format string:\ Start by creating a format string with placeholders. Placeholders are denoted using
%followed by a formatting specifier. For example,%sis used for strings,%dfor integers,%ffor floating-point numbers, etc. Here's an example format string:val formatString = "Hello, %s! You are %d years old."Create a formatter object:\ Initialize a
Formatterobject by passing the format string to its constructor:val formatter = Formatter()Format the string:\ Use the
format()method of theFormatterclass to substitute the placeholders with actual values. Pass the formatted string and the values as arguments to theformat()method:val name = "John"
val age = 30
val formattedString = formatter.format(formatString, name, age).toString()In this example, the
%splaceholder is replaced by the value ofname, and the%dplaceholder is replaced by the value ofage.Print or use the formatted string:\ You can now use the
formattedStringvariable 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.
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.