在kotlin
中,我想过滤一个字符串并返回仅有效字符的子字符串。假设我们有有效的字符,
valid = listOf('A', 'B', 'C')
如何以最简洁的方式在kotlin中定义fcn
来过滤字符串并仅保留有效字符?例如,
'ABCDEBCA' --> 'ABCBCA'
'AEDC' --> 'AC'
无需使用字符串数组就无法找到规范的方法来执行此操作。
import kotlin.text.filter
class Test(){
val VALID = listOf("A", "B", "C")
fun filterString(expression: String): String{
expression.filter(x --> !VALID.contains(x)) #Doesn't work
}
}
filter docs并未显示任何专门针对弹簧操作的示例。
答案 0 :(得分:5)
val VALID = setOf('A', 'B', 'C') // lookup in a set is O(1), whereas it's O(n) in a list. The set must contain Chars, not Strings
val expression = "ABCDEFEDCBA"
val filtered = expression.filter { VALID.contains(it) }
println(filtered)
// ABCCBA
或者
val VALID = setOf('A', 'B', 'C')
fun filterString(expression: String) = expression.filter { it in VALID }
fun main(args: Array<String>) {
val expression = "ABCDEFEDCBA"
val filtered = filterString(expression)
println(filtered)
// ABCCBA
}