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.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,568 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Sam of Simple Samples 5,516 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.


  2. Karen Payne MVP 35,031 Reputation points
    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