Kotlin commonPrefixWith用法及代码示例

126 阅读1分钟

本文方法及代码示例基于 Kotlin 2.1.20 Released

commonPrefixWith 所在包 kotlin.text.commonPrefixWith,其相关用法介绍如下:

用法:

fun CharSequence.commonPrefixWith(
    other: CharSequence, 
    ignoreCase: Boolean = false
): String

返回最长的字符串 prefix 使得这个 char 序列和 other char 序列都以此前缀开头,注意不要拆分代理对。如果 this 和 other 没有公共前缀,则返回空字符串。

代码示例:

import java.util.Locale
import kotlin.test.*

fun main(args: Array<String>) {
    //sampleStart
    println("Hot_Coffee".commonPrefixWith("Hot_cocoa")) // Hot_
    println("Hot_Coffee".commonPrefixWith("Hot_cocoa", true)) // Hot_Co
    println("Hot_Coffee".commonPrefixWith("Iced_Coffee")) //
    //sampleEnd
}

// 输出
Hot_
Hot_Co

参数:ignoreCase-true 匹配字符时忽略字符大小写。默认false.

相关方法