In kotlin
I'd like to filter a string and return a substring of only valid characters. Say we have valid characters,
valid = listOf('A', 'B', 'C')
How can I define a fcn
in kotlin in the most succinct way to filter a string and only retain valid characters? For example,
'ABCDEBCA' --> 'ABCBCA'
'AEDC' --> 'AC'
Having trouble finding a canonical way to do this without resorting to using an array of string.
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
}
}
The filter docs doesn't show any examples specifically for spring manipulation.
To get substring of a String in Kotlin, use String.subSequence () method. Given a string str1, and if we would like to get the substring from index startIndex until the index endIndex, call subSequence () method on string str1 and pass the indices startIndex and endIndex respectively as arguments to the method as shown below.
The standard Kotlin library provides many beneficial functions to filter a List. These functions return a new List and are usable for both read-only and mutable Lists. We use predicates to define the filtering conditions. The predicates are simple lambda expressions.
Given a string str1, and if we would like to filter the characters of this string using a predicate (some condition) predicate, call filter () method on string str1 and pass the predicate predicate as argument to the method as shown below. filter () method returns a filtered String value based on the predicate.
filter () method returns a filtered String value based on the predicate. In this example, we will take a string in str1, and filter only digits using String.filter () method.
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
Or
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With