How to format a string in Kothin? Formatting string is a standard operation in most programming languages, including Kotlin. In Kotlin, you can use the String.format() function or the string interpolation feature to format strings. Formatting involves concatenating strings, padding strings with whitespace, formatting the decimal numbers, etc.
Formatting strings in Kotlin helps you to create dynamic outputs which well-structured codes easily. Apart from that, the methods also allow you to control the precision of the Numbers, align the texts, etc. Kotlin offers us several ways to format strings hence, in this article, we will discuss all the different ways to format strings with examples.
1. Format String Using Interpolation In Kotlin
One of the simplest ways to perform string formatting is through string interpolation. This allows you to embed the expressions and variables directly within the string. The advantage of this technique is that you can easily concatenate the variables, constants, etc. Traditionally to join them, we can use a comma(,), but the string interpolation is more convenient and easy to use. To use string interpolation, prefix the variable or expression with the dollar sign ($) inside the string.
1.1 Syntax
Following is a syntax of the string interpolation.
// Syntax
“${variable}”
Here, variable is the variable’s name that we need to concatenate with the string. Note that the variable can be any data type. We do not need to use the curly brackets if only a single variable exists. If it is an expression instead of a single variable then we must enclose it within the curly brackets otherwise, Kotlin will throw an error or considers the entire expression as a String.
1.2 Example
// Example of String Formatting in Kotlin Using String Interpolation.
// Declare the values
val name = “John”
val age = 30
// Format the String using String Interpolation
val message = “My name is $name, and I am $age years old.”
println(message)
Yields below output.
2. Format String Using Templates In kotlin
String templates are another alternative way for string manipulation. This takes an expression enclosed by the closing brackets – [ & ].
2.1 Syntax
// Syntax
“${“$%.nf”.format(variable)}”
The expression “${}” indicates this is a string template. %.nf is a format specifier for a floating-point number with n decimal places. The variable represents the value that we need to format. Note that the variable here should be a Number data type.
2.2 Example
// Example of String Formatting in Kotlin Using String Template.
// Declare the values
val quantity = 5
val price = 9.99
val total = quantity * price
// Perfom String Formatting using String Template
val message = “The total cost for $quantity items is ${“$%.2f”.format(total)}”
println(message)
Yields below output.
3. Using string format() Method In Kotlin
In class, the string data type is treated as an object hence, Koltin offers several in-built methods to the string. One such method is Kotlin string.format() that we can use to format string.
3.1 Syntax of string.format()
Following is the syntax of the string.format() method
//Syntax
String.format(“%.nf”, variable)
Here String is the keyword of Kotlin. “%.nf” specifies that we need the Number truncated to n decimal places. The variable represents the value that we need to format into the string.
3.2 Example
// Example of String Formatting in Kotlin Using String format Method
// Declare the values of the variables
val pi = 3.14159
// Use format method to format the String.
val formattedPi = String.format(“%.2f”, pi)
println(“The value of pi is $formattedPi”)
Output:
3.3 Type Specifiers
Kotlin allows us to format all kinds of data types ranging from boolean, integers, decimal numbers etc by using string.format(). For different data types, we can use different notations within the String. Below is a list of supported notations and the corresponding data types we can format:
%b – Boolean%c – Characters (enclosed by ‘ ‘)%d – Signed integers like 1,2,14%e – Floating point Numbers in Scientific Notations e.g 1.5e12%f – Floating point Numbers in Decimal Format like 45.2341%g – Floating point Numbers either in the Decimal or Scientific value depending upon how large the value is.%h – Hash code of the given argument%n – Newline character%o – Octal Integers (Integers having base 8)%s – String data types.%t – Date or Time in date time format%x – Hexadecimal Integers with base 16String Format Type Specifiers in Kotlin
Following is an example using some of the above type specifiers.
// Example to demonstrate String Formatting with other data types
import java.text.SimpleDateFormat
import java.util.*
fun main() {
// Declare variables of different types
val boolValue = true
val charValue = ‘A’
val intValue = -42
val floatValue = 3.14159f
val stringValue = “Hello, World!”
val dateValue = Date()
val hexValue = 255
// Print values using different format specifiers
println(“Boolean: %b”.format(boolValue)) // Format a boolean value
println(“Character: %c”.format(charValue)) // Format a character value
println(“Signed Integer: %d”.format(intValue)) // Format a signed integer value
println(“Float in Scientific Notation: %e”.format(floatValue)) // Format a float value in scientific notation
println(“Float in Decimal Format: %f”.format(floatValue)) // Format a float value in decimal format
println(“Float in Decimal or Scientific Notation: %g”.format(floatValue)) // Format a float value in decimal or scientific notation
println(“Hashcode: %h”.format(stringValue)) // Format the hashcode of a string value
println(“Newline Separator: %n”) // Print a newline separator
println(“Octal Integer: %o”.format(intValue)) // Format an integer value in octal format
println(“String: %s”.format(stringValue)) // Format a string value
println(“Date: ${SimpleDateFormat(“yyyy-MM-dd”).format(dateValue)}”) // Format the date value using SimpleDateFormat
println(“Hexadecimal Integer: %x”.format(hexValue)) // Format an integer value in hexadecimal format
}
By running the above code, you will get the following output.
4. Format The String Using Padding In Kotlin
As a coder, most of the time you may need to add whitespace to the string. Kotlin allows us to perform this operation through the format() string method. Adding whitespace manually is not a good coding practice because it makes the code unstructured and less readable.
Syntax:
# Syntax
“|String.format(“%-ns”, variable)|””
Here the Sting is a keyword. “%-ns” indicates the total space we want the variable to occur inside the string. n specifies the minimum space the string should occupy. Note that if the value of n is less than the string, there will be no whitespace. The variable is the Number that we need to format in the string. Notice that we should enclose the entire expression within “|”.
Example
// Example to demonstrate String Formatting in Kotlin Using Padding
// Declare the values of the variables
val name = “John”
val paddedName = String.format(“%-10s”, name)
println(“|$paddedName|”)
Output:
5. Frequently Asked Questions
In Kotlin, you can use the String.format() function or the string interpolation feature to format strings.
To format strings in Kotlin, you can easily perform either by using String.format() function or the string interpolation.
Conclusion
This article taught us how to format strings in Kotlin through various methods. Kotlin offers several ways to perform string formatting like string interpolation, string template, in-built format method, etc., so the technique helps the coders to present the data clearly and concisely. Kotlin string format is a way to create a formatted string by replacing placeholders in the string with values provided by the user.
More Resources:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/format.htm
How to format a string in Kothin? Formatting string is a standard operation in most programming languages, including Kotlin. In Kotlin, you can use the String.format() function or the string interpolation feature to format strings. Formatting involves concatenating strings, padding strings with whitespace, formatting the decimal numbers, etc. Formatting strings in Kotlin helps you to Read More Kotlin, Kotlin String