An example. First, here we locate the first index of a String in a source String. We search for the location of "dog" with the IndexOf function.
Part 1 We call IndexOf to search for a substring. The string "dog" is found in the input String, at index 4.
Part 2 If the string is not found, the result is -1. Often this is an important thing to test.
Module Module1
Sub Main()
Dim animals As String = "cat,dog"' Part 1: print index of dog.
Console.WriteLine(animals.IndexOf("dog"))
' Part 2: call IndexOf on value not present.
If animals.IndexOf("frog") = -1 Then
Console.WriteLine("?")
End If
End Sub
End Module4
?
Loop. Sometimes we need to locate the first index of a String, and then continue locating further instances. We can do this with a Do While construct and IndexOf().
Step 1 The program declares a String, which contains the letter "t" in 2 places.
Step 2 We call IndexOf on the String. This gives us the first index of a lowercase T character.
Step 3 The Do While loop continues until IndexOf returns negative 1. If the letter never occurs, the loop body is not entered.
Module Module1
Sub Main()
' Step 1: the input String.
Dim s As String = "dotnet"' Step 2: the iteration variable.
Dim i As Integer = s.IndexOf("t"c)
' Step 3: loop over the found indexes.
Do While (i <> -1)
' Write the substring.
Console.WriteLine(s.Substring(i))
' Get next index.
i = s.IndexOf("t"c, i + 1)
Loop
End Sub
End Moduletnet
t
Return value. IndexOf returns -1, a special value, when no result is found. Otherwise, it returns the index of the string that is found within the source string.
Module Module1
Sub Main()
Dim source As String = "orange cat"' See IndexOf function results.
Console.WriteLine("NOT FOUND: {0}", source.IndexOf("dog"))
Console.WriteLine("FOUND: {0}", source.IndexOf("cat"))
End Sub
End ModuleNOT FOUND: -1
FOUND: 7
IndexOf, Substring. Here we use the Substring function with the result of IndexOf. The IndexOf call here locates the first index of the uppercase letter B in the source string.
Module Module1
Sub Main()
' The string you are searching.
Dim s As String = "Visual Basic rocks"' Find index of uppercase letter B.
Dim i As Integer = s.IndexOf("B"c)
' This new string contains the substring starting at B.
Dim part As String = s.Substring(i)
Console.WriteLine(part)
End Sub
End ModuleBasic rocks
Benchmark, Char. Often we can use a Char instead of a one-character String. In some cases, the character overload is many times faster. It will return an equivalent value.
Version 1 In this version of the code, we pass a Char to IndexOf and test the result value against negative 1.
Version 2 This code uses a single-character string as the argument. The end result is the same as version 1, but the performance is worse.
Result It is much faster to search for a Char, not a 1-letter String. This optimization can help many programs.
Module Module1
Sub Main()
Dim letters As String = "abcdef"
Dim m As Integer = 10000000
' Version 1: use char argument with IndexOf.
Dim s1 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
If letters.IndexOf("f"c) = -1 Then
Return
End If
Next
s1.Stop()
' Version 2: use string argument with IndexOf.
Dim s2 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
If letters.IndexOf("f") = -1 Then
Return
End If
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
End Sub
End Module4.98 ns IndexOf(Char)
126.90 ns IndexOf(String)
IndexOfAny. This receives an array of Chars as the argument. It then returns the index of the first one found. This is a way to simplify a search for multiple values.
Return The result value from IndexOfAny should be checked for -1 each time it is called. Use an If-statement.
Tip Always check for -1, because many times using -1 elsewhere in your application will cause an error. It represents a not-found result.
Warning The -1 value returned by IndexOf and methods such as IndexOfAny has caused countless bugs.
Module Module1
Sub Main()
' The input String.
Dim s1 As String = "The cat is hungry."' Find the first index of either "x" or "n"
Dim i1 As Integer = s1.IndexOfAny(New Char() {"x"c, "n"c})
If (i1 <> -1) Then
Console.WriteLine(s1.Substring(i1))
End If
' Another input String.
Dim s2 As String = "C# is challenging."
' Find the first index of either '#' or ' '
Dim i2 As Integer = s2.IndexOfAny(New Char() {"#"c, " "c})
If (i2 <> -1) Then
Console.WriteLine(s2.Substring(i2))
End If
End Sub
End Modulengry.
# is challenging.
Array.IndexOf. A separate IndexOf function exists on the Array class. This method is shared, so we access it as "Array.IndexOf." It works in a similar way as string IndexOf.
A summary. We checked IndexOf's result, which is negative one if the argument is not found. This function can simplify a program. It can replace many For-loops that search strings.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 15, 2023 (simplify).