String functions in Kotlin with example

length: This function returns the length of the string.

val str = "Hello, World!"
println(str.length) // Output: 13

isEmpty: This function returns true if the string is empty.

val str1 = ""
val str2 = "Hello, World!"
println(str1.isEmpty()) // Output: true
println(str2.isEmpty()) // Output: false

isBlank: This function returns true if the string is empty or consists of whitespace characters only.

val str1 = ""
val str2 = " "
val str3 = "Hello, World!"
println(str1.isBlank()) // Output: true
println(str2.isBlank()) // Output: true
println(str3.isBlank()) // Output: false

substring: This function returns a substring of the given string.

The substring function is used to extract a substring from a given string. It takes one or two arguments, depending on how you want to use it:

If you pass only one argument to substring, it will return a substring starting from the specified index to the end of the string.

val str = "Hello, World!"
val sub = str.substring(7) // returns "World!"

In this example, substring returns the substring starting from index 7 (which is the ‘W’ character in “World!”) to the end of the string.

If you pass two arguments to substring, it will return a substring starting from the first index to the second index (excluding the character at the second index).

val str = "Hello, World!"
val sub = str.substring(0, 5) // returns "Hello"

In this example, substring returns the substring starting from index 0 (which is the ‘H’ character in “Hello, World!”) to index 5 (excluding the character at index 5, which is the comma), so it returns “Hello”.

It’s worth noting that substring throws an IndexOutOfBoundsException if you pass invalid indexes as arguments. For example:

val str = "Hello, World!"
val sub = str.substring(7, 20) // throws IndexOutOfBoundsException

In this example, substring tries to return a substring starting from index 7 and ending at index 20, but the string “Hello, World!” only has 12 characters, so the second argument is invalid and substring throws an exception.

replace: This function replaces all occurrences of a specified string or regular expression with another string.

val str = "Hello, World!"
println(str.replace("World", "Kotlin")) // Output: Hello, Kotlin!

toUpperCase/toLowerCase: These functions convert the string to uppercase or lowercase.

val str = "Hello, World!"
println(str.toUpperCase()) // Output: HELLO, WORLD!
println(str.toLowerCase()) // Output: hello, world!

trim: This function removes leading and trailing whitespace characters from the string.

val str = "  Hello, World!  "
println(str.trim()) // Output: Hello, World!