How to VB.NET String.Contains()

The Contains() method is a built-in function of the String class in VB.NET. It's used to determine if a specific substring (smaller string) exists within a given source string. It essentially performs a search operation to check for the presence of the substring.

System.String.Contains(String str) As Boolean
Parameters:
  1. String str - input String for search
Returns:
  1. Boolean - Yes/No.

Functionality

  1. It takes a single argument, which is the substring you want to search for within the source string.
  2. The search is performed in a case-sensitive manner by default. This means that "Hello" and "hello" would be considered different substrings.
  3. If the entire substring is found anywhere within the source string, the method returns True.
  4. Conversely, if the substring is not found or if the source string is empty, the method returns False.
Example:
Dim sourceString As String = "This is a sample string." Dim subString As String = "sample" Dim isContained As Boolean = sourceString.Contains(subString) ' True

In this example:

  1. sourceString holds the string to be searched.
  2. subString holds the substring to be searched for.
  3. isContained is a Boolean variable that will store the result (True if found, False otherwise).
Exceptions:
System.ArgumentNullException :If the argument is null.
Key Points:
  1. Case Sensitivity: By default, Contains() performs a case-sensitive search. To achieve a case-insensitive search, you can convert either the source string or the substring to lowercase before using Contains().
  2. Partial Matches: The method only checks for the exact presence of the entire substring. It doesn't identify occurrences where the substring forms part of a larger word within the source string (e.g., "sample" wouldn't be found in "sampling").
Example with Case-Insensitive Search:
Dim message As String = "Welcome to VB.NET!" Dim searchTerm As String = "vb.net" ' Lowercase search term Dim isFound As Boolean = message.ToLower().Contains(searchTerm.ToLower()) ' True (case-insensitive)
Full Source VB.NET
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.Contains("TOP") = True Then MsgBox("The string Contains() 'TOP' ") Else MsgBox("The String does not Contains() 'TOP'") End If End Sub End Class
Common Use Cases:
  1. Validating user input: You can use Contains() to check if a user-entered value includes a specific term or pattern.
  2. Searching text content: It's helpful for tasks like searching for keywords within documents or code.
  3. String manipulation: Combined with other string methods, Contains() can be used for various string processing tasks.

Conclusion

The VB.NET String.Contains() method is used to determine whether a specified substring is present within a given string, returning a Boolean value indicating its existence or absence.