Share via

Split String

JasonDaurison 116 Reputation points
2021-05-23T20:10:20.923+00:00

Hello everyone,

I was wondering if there is a way to determine if a string contains a value in a array without using a loop. Does the array class have a function for that?

Thanks.

Developer technologies | VB

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,606 Reputation points Volunteer Moderator
    2021-05-24T00:20:48.947+00:00

    You can use .Contains extension.

    • First example finds karen againsts Karen because of the comparer
    • Second example does not as strings are case sensitive.

    So it's wise to know if an exact match is needed or not.

    Dim findThisName = "Karen"
    Dim someArray = New String() {"karen", "bill", "mary"}
    
    Dim test = someArray.Contains(findThisName, StringComparer.OrdinalIgnoreCase)
    If test Then
        Console.WriteLine($"{findThisName} was found case insensitive")
    Else
        Console.WriteLine($"{findThisName} was not found case insensitive")
    End If
    
    test = someArray.Contains(findThisName)
    If test Then
        Console.WriteLine($"{findThisName} was found case sensitive")
    Else
        Console.WriteLine($"{findThisName} was not found case sensitive")
    End If
    

  2. Sam of Simple Samples 5,586 Reputation points
    2021-05-23T21:00:03.017+00:00

    You can do something like:

    searchstrings.Find(Function(f) s1.Contains(f))
    

    The following is a complete sample.

    Dim s1 As String = "RedGreenBlue"
    Dim s2 As String = "BlackWhite"
    Dim searchstrings As New List(Of String) From {"Blue", "Orange"}
    Dim v As String
    v = searchstrings.Find(Function(f) s1.Contains(f))
    Console.WriteLine("Found {0}",If(v Is Nothing, "nothing", v))
    v = searchstrings.Find(Function(f) s2.Contains(f))
    Console.WriteLine("Found {0}",If(v Is Nothing, "nothing", v))
    

    See FindStringInArrayInStringVB for a fiddle you can use to try it.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.