StartsWith
, EndsWith
In VB.NET StartsWith
tests the first part of a String
. It checks whether one String
starts with the characters in another. EndsWith
checks the last characters.
StartsWith
is often useful. StartsWith
supports the StringComparison.OrdinalIgnoreCase argument, which makes it case-insensitive. Without this argument, it is case-sensitive.
Here we use StartsWith
. This call is case-sensitive. We pass the StringComparison.OrdinalIgnoreCase enumerated constant. This makes "D" equal to "d" so StartsWith
returns True.
StartsWith
can also return False if the first String
does not actually start with the second String
.Module Module1 Sub Main() Dim value As String = "Dot Net Perls" ' Use StartsWith. If value.StartsWith("Dot") Then Console.WriteLine(1) End If ' Use StartsWith ignoring case. If value.StartsWith("dot", StringComparison.OrdinalIgnoreCase) Then Console.WriteLine(2) End If ' It can return False. Console.WriteLine(value.StartsWith("Net")) End Sub End Module1 2 False
There is another way to check the first characters of a String
. It is typically much faster. We test the Length
of a String
and then check characters by their indexes.
If
-statements shown here will always evaluate to the same truth value.Module Module1 Sub Main() Dim value As String = "cat" ' You could use StartsWith... If value.StartsWith("c") Then Console.WriteLine(1) End If ' Or you could check the character yourself. If value.Length >= 1 And value(0) = "c" Then Console.WriteLine(2) End If End Sub End Module1 2
EndsWith
This tests the end part of a String
. With it we specify a String
that is then tested against the end characters of the first String
.
String
containing the address of this web site.For-Each
loop construct to loop through all the possible extensions and then use EndsWith
on the first String
.Module Module1 Sub Main() Dim value As String = "http://www.dotnetperls.com" Dim array() As String = {".net", ".org", ".edu", ".com"} For Each element As String In array If value.EndsWith(element) Then Console.WriteLine(element) End If Next End Sub End Module.com
StringComparison
You can pass a StringComparison
enum
as the second argument. The two most useful options are probably StringComparison.Ordinal
and StringComparison.OrdinalIgnoreCase.
We looked at the StartsWith
and EndsWith
methods. EndsWith
is excellent for testing to see whether a String
happens to start (or end) with another String
.