Android Code Snippet Filter - (similar to the VB.Net Filter function)

LucaMs

Expert
Licensed User
Sub Name: Filter

Description: Returns a String Array containing a subset of the String Array passed as parameter according to the specified filter (Match parameter).

Parameters:
Strings() - the "source" String Array
Match - the String filter
Include - whether to return an array containing Match or that does not contain it
CaseSensitive - if take into account the difference between upper and lower case


B4X:
Sub Filter(Strings() As String, Match As String, Include As Boolean, CaseSensitive As Boolean) As String()
    Dim lstResult As List : lstResult.Initialize
    Dim Valid As Boolean

    If Not(Include) Then
        For i = 0 To Strings.Length - 1
            lstResult.Add(Strings(i))
        Next
    End If

    For i = 0 To Strings.Length - 1
        Valid = False
        If CaseSensitive Then
            If Strings(i) = Match Then
                Valid = True
            End If
        Else
            If Strings(i).ToLowerCase = Match.ToLowerCase Then
                Valid = True
            End If
        End If
   
        If Valid Then
            If Include Then
                lstResult.Add(Strings(i))
            Else
                lstResult.RemoveAt(lstResult.IndexOf(Strings(i)))
            End If
        End If
    Next

    Dim Result(lstResult.Size) As String

    For i = 0 To lstResult.Size - 1
        Result(i) = lstResult.Get(i)
    Next

    Return Result

End Sub

Example:
B4X:
    Dim Strings(5) As String

Strings(0) = "This"
Strings(1) = "is"
Strings(2) = "just"
Strings(3) = "an"
Strings(4) = "example"

Dim Result() As String = Filter(Strings, "Is", True, False)
' Returns: "is"

Dim Result() As String = Filter(Strings, "Is", True, True)
' Returns: [empty array]
Log("length= " & Result.Length)

Dim Result() As String = Filter(Strings, "Is", False, False)
' Returns: "This" "just" "an" "example"


Tags: Filter, String, Strings, Texts, Array, Regex
 
Last edited:
Top