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.

shadow-left