Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a substring in kotlin

Tags:

kotlin

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.

like image 730
Adam Hughes Avatar asked Feb 14 '17 17:02

Adam Hughes


People also ask

How to get substring of a string in Kotlin?

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.

How to filter a list in Kotlin?

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.

How to filter the characters of string using predicate in JavaScript?

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.

What is the use of filter () method in JavaScript?

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.


1 Answers

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
}
like image 112
JB Nizet Avatar answered Sep 18 '22 14:09

JB Nizet