How to VB.NET String.IndexOf()

The IndexOf method in the String Class is used to determine the position or index of the first occurrence of a specified substring within a given string. It returns the index value where the substring is found, or -1 if the substring is not present.

System.String.IndexOf(String str) As Integer
Parameters:
  1. str - The parameter string to check its occurrences.
Returns:
  1. Integer - If the parameter String occurred as a substring in the specified String

It returns position of the first character of the substring .

If it does not occur as a substring, -1 is returned.

Exceptions: System.ArgumentNullException: If the Argument is null.

For ex:

"This is a test".IndexOf("Test") returns 10

"This is a test".IndexOf("vb") returns -1

IndexOf method in VB.NET

Here is an example to illustrate the usage of the IndexOf method in VB.NET:

Dim sentence As String = "The quick brown fox jumps over the lazy dog" Dim searchTerm As String = "fox" Dim index As Integer = sentence.IndexOf(searchTerm) If index <> -1 Then Console.WriteLine("The substring '{0}' was found at index {1}.", searchTerm, index) Else Console.WriteLine("The substring '{0}' was not found.", searchTerm) End If

In the above example, we have a sentence string that contains the phrase "The quick brown fox jumps over the lazy dog". We want to find the index position of the substring "fox" within the sentence.

The IndexOf method is called on the sentence string, passing the searchTerm "fox" as the argument. The method searches for the first occurrence of the substring "fox" within the sentence and returns the index value where it is found.

If the substring is found (i.e., the index value is not -1), the program prints a message indicating the position of the substring within the sentence. Otherwise, if the index value is -1, it means that the substring is not present in the sentence, and a different message is printed.

In this case, the output will be:

The substring 'fox' was found at index 16.

Conclusion

The IndexOf method is a useful tool when you need to determine the position of a specific substring within a larger string. It allows you to perform search operations and retrieve the index value, which can be used for further manipulation or analysis of the string data.