VB.NET Contains ExampleUse the Contains Function on the String type to see if a substring is found.
dot net perls

Contains determines if a substring exists in a source string. The Contains method provides a clearer name for this. It returns a Boolean that indicates whether the argument string was located in the instance string.


In this example, we see that there are 2 subroutines defined. The Test subroutine receives one input string. It prints this to the screen and then invokes the Contains method on it, using different search arguments.


Then The method will determine if the case-sensitive strings "Net", "perls", or "Dot" are located in the string.

And Because it is called twice, we can test the Contains method's correctness.

VB.NET program that uses Contains method
Module Module1 Sub Main() ' Call the Test sub with different string literal arguments. Test("Dot Net Perls") Test("dot net perls") End Sub Sub Test(ByVal input As String) ' Write the formal parameter. Console.Write("--- ") Console.Write(input) Console.WriteLine(" ---") ' See if it contains this string. Dim net As Boolean = input.Contains("Net") Console.Write("Contains 'Net': ") Console.WriteLine(net) ' See if it contains this string. If input.Contains("perls") Then Console.WriteLine("Contains 'perls'") End If ' See if it does not contain this string. If Not input.Contains("Dot") Then Console.WriteLine("Doesn't Contain 'Dot'") End If End Sub End Module
--- Dot Net Perls --- Contains 'Net': True --- dot net perls --- Contains 'Net': False Contains 'perls' Doesn't Contain 'Dot'

You can either directly test the result of the Contains method, or store it in a local variable (or field). If you store it, you will not have to execute the internal logic of the method more than once. This can improve tight loops.

Summary. We described the Contains Function and demonstrated its usage. We also showed how its Boolean result can be stored in memory for later reuse. IndexOf can also search strings.


© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.