Search

Dark theme | Light theme
Showing posts with label KotlinKandy:Strings. Show all posts
Showing posts with label KotlinKandy:Strings. Show all posts

April 4, 2026

Kotlin Kandy: Get Text Before Or After A Delimiter

Kotlin adds the substringBefore, substringBeforeLast, substringAfter and substringAfterLast extension functions to the String class. Instead of using indices to get a substring you can use a string or character value. The functions without Last use the first occurrence of the delimiter and the methods with Last use the last occurrence. If the delimiter is not found the original string is returned. You can supply a value that should be returned when the delimiter is not found.

December 15, 2022

Kotlin Kandy: Split Collection Or String With Partition

The method partition is available in Kotlin for arrays and iterable objects to split it into two lists. We pass a predicate lambda function to the partition method. The predicate should return either true or false based on a condition for each element from the array or iterable. The return result is a Pair instance where the first element is a List object with all elements that returned true from the predicate. The second element in the Pair object contains all elements for which the predicate returned false. As a String can be seen as an iterable of characters we can also use partition on a String instance.

In the following example code we use partition on different objects:

// Create an infinite sequence of increasing numbers.
val numbers = generateSequence(0) { i -> i + 1 }

// We take the first 20 numbers from our sequence and
// partition it to two pairs.
// First element of the pair is a list of all even numbers,
// second element is the list of all odd numbers.
// We use destructurizing to assign the pair values to
// variables even and odd.
val (even, odd) = numbers.take(20)
    .partition { n -> n % 2 == 0}

assert(even == listOf(0, 2, 4, 6, 8, 10, 12, 14, 16, 18))
assert(odd == listOf(1, 3, 5, 7, 9, 11, 13, 15, 17, 19))


// Sample map with data.
val data = mapOf("language" to "Java", "username" to "mrhaki", "age" to 49)

// We can also use partition on the entries of the map.
val (stringValues, nonStringValues) = data.entries.partition { entry -> entry.value is String }

assert(stringValues.associate { it.toPair() } == mapOf("language" to "Java", "username" to "mrhaki"))
assert(nonStringValues.associate { it.toPair() } == mapOf("age" to 49))


// Sample string to use with partition.
val s = "Kotlin kandy!"

// We can also use partition on a string where
// the predicate is applied for each character.
val (letters, others) = s.partition(Char::isLetter)

assert(letters == "Kotlinkandy")
assert(others == " !")

Written with Kotlin 1.7.20.

December 14, 2022

Kotlin Kandy: Taking Or Dropping Characters From A String

Kotlin adds a lot of extension methods to the String class. For example we can use the take method to get a certain number of characters from the start of a string value. With the drop method where we remove a given number of characters from the start of the string to get a new string. We can also take and drop a certain number of characters from the end of a string using the methods takeLast and dropLast.

Instead of using the number of characters we want to take or drop we can also use a condition defined with a predicate lambda function. We take or drop characters as long as the lambda returns true. The names of the methods for taking characters are takeWhile and takeLastWhile and for dropping characters dropWhile and dropLastWhile.

In the following example we use different methods to take and drop characters from a string value to get a new string value:

val s = "Kotlin kandy!"

// Take the first 6 characters.
assert(s.take(6) == "Kotlin")

// Take the last 6 characters.
assert(s.takeLast(6) == "kandy!")

// Take characters until lowercase k is encountered.
assert(s.takeWhile { it != 'k'} == "Kotlin ")

// Take characters from the end of the string
// to the beginning until a space is encountered.
assert(s.takeLastWhile { it != ' '} == "kandy!")


// Drop the first 7 characters.
assert(s.drop(7) == "kandy!")

// Drop the last 7 characters.
assert(s.dropLast(7) == "Kotlin")

// Drop characters until a lowercase k is encountered.
assert(s.dropWhile { it != 'k'} == "kandy!")

// Drop characters starting at the end of the string
// until a space is encountered.
assert(s.dropLastWhile { it != ' '} == "Kotlin ")

Written with Kotlin 1.7.20.

December 13, 2022

Kotlin Kandy: Find Common Prefix Or Suffix In Strings

If we want to find the longest shared prefix or suffix for two string values we can use the String extension methods commonPrefixWith and commonSuffixWith. The result is the prefix or suffix value that is common for both values. We can pass a second argument to the method to indicate if we want to ignore the casing of the letters. The default value for this argument is false, so if we don’t set it explicitly the casing of the letters should also match.

In the following example we use the commonPrefixWith and commonSuffixWith methods:

// Find the common prefix of 2 strings.
assert("Sample text".commonPrefixWith("Sampler") == "Sample")

// The second argument can be used to ignore the case
// of letters. By default this is false.
assert("sample text".commonPrefixWith("Sampler", true) == "sample")
assert("sample text".commonSuffixWith("Sampler") == "")


// Find the common suffix of 2 strings.
assert("Sample string".commonSuffixWith("Example thing") == "ing")


// Sample list of string values with a common prefix.
// We want to find the common prefix for these string values.
val values = listOf("Sample value", "Salt", "Sample string", "Sampler")

val commonPrefix = values
    // Combine each value with the next in a pair
    .zipWithNext()
    // Transform each pair into the common prefix of the
    // first and second element from the pair.
    .map { pair -> pair.first.commonPrefixWith(pair.second) }
    // The shortest common prefix is the winner.
    .minBy { common -> common.length }

assert(commonPrefix == "Sa")

Written with Kotlin 1.7.2.0.

December 10, 2022

Kotlin Kandy: Padding Strings

Kotlin extends the String class with a couple of padding methods. These methods allows us to define a fixed width a string value must occupy. If the string itself is less than the fixed width then the space is padded with spaces or any other character we define. We can pad to the left or the right of the string using the padStart and padEnd methods. When we don’t define an argument a space character is used for padding, but we can also add our own custom character as argument that will be used as padding character.

In the following example code we use the padEnd and padStart methods with and without arguments:

assert("Kotlin".padEnd(12) == "Kotlin      ")
assert("Kotlin".padStart(12) == "      Kotlin")

assert("Kotlin".padEnd(12, '-') == "Kotlin------")
assert("Kotlin".padStart(12, '.') == "......Kotlin")

val table = listOf(
    Triple("page1.html", 200, 1201),
    Triple("page2.html", 42, 8853),
    Triple("page3.html", 98, 3432),
    Triple("page4.html", 432, 900)
)

val output = table.map { data: Triple<String, Int, Int> ->
    data.first.padEnd(14, '.') +
            data.second.toString().padStart(5, '.') +
            data.third.toString().padStart(8)
}.joinToString(System.lineSeparator())

print(output)

assert(output == """
page1.html......200    1201
page2.html.......42    8853
page3.html.......98    3432
page4.html......432     900
""".trimIndent())

Written with Kotlin 1.7.20.

December 9, 2022

Kotlin Kandy: Strip Leading Spaces From Multiline Strings

Multiline strings are very useful. But sometimes we want use the multiline string without the leading spaces that are added because of code formatting. To remove leading spaces we can use the trimIndent method. This method will find the least amount of leading spaces and removes that amount of spaces from each line. Also a first and last empty line are removed.

If we want a bit more control we can also add a character to the start of each line to show where the line starts. And then we use the method trimMargin and all spaces before that character are removed. The default character is the pipe symbol, |, but we can also define our own and pass it as argument to the trimMargin method.

In the following example code we use the trimIndent and trimMargin methods:

// trimIndent will remove spaces from the beginning
// of the line based on the least number of spaces.
// The first and last empty line are also removed
// from the string.
fun createText(): String {
    return """
        Multiline string
          with simple 2 spaces
        indentation.
    """.trimIndent()
}

assert(createText() == """Multiline string
  with simple 2 spaces
indentation.""")

// trimMargin will trim all spaces before
// the default margin character |.
val languages = """
    |Kotlin
    |Groovy
    |Clojure
      |Java
""".trimMargin()

assert(languages == """Kotlin
Groovy
Clojure
Java""")

// We can use our own margin character by
// specifying the character as argument
// to the trimMargin method.
val buildTools = """
    >Gradle
    >Maven
      >SBT
    >Leiningen
""".trimMargin(">")

assert(buildTools == """Gradle
Maven
SBT
Leiningen""")

Written with Kotlin 1.7.20.