String.Contains() method with example in C#

C# String.Contains() strategy: Here, we will find out about the Contains() technique for String class with example.

C# String.Contains() Method

String.Contains() technique is utilized to check whether a given string contains a substring or not, we can utilize this strategy when we have to check whether a piece of the string (substring) exists in the string.

Syntax:

    bool String.Contains(String substring);

The technique is called with “this” string, for example, the string where we need to check the substring.

Parameter:

  • substring – is the piece of the string to be checked.
  • Return value: bool – it returns “Genuine” if a substring exists in the string or it returns “Bogus” if the substring doesn’t exist in the string.

Note: This strategy is case-delicate.

Example:

    Input:
    string str  = "Hello world!";
    string str1 = "world";
    string str2 = "Hi";
    
    Function call:
    str.Contains(str1);
    str.Contains(str2);

    Output:
    True
    False

C# Example to change over the string to characters cluster utilizing String.Contains() technique:

Example 1:

using System;
class JustTechReview
{
    static void Main()
    {
        // declaring string variables
        string str = "Hello world!";
        string str1 = "world";
        string str2 = "Hi";

        // checking substring
        Console.WriteLine("str.Contains(str1): " + str.Contains(str1));
        Console.WriteLine("str.Contains(str2): " + str.Contains(str2));
    }
}

Output:

str.Contains(str1): True
str.Contains(str2): False

Example 2:

using System;
class JustTechReview
{
    static void Main()
    {
        // declaring string variables
        string address = "16/1 Ganesh Chandra Avenue, Kolkata-700013";
        string area1 = "Sunrise Apt.";
        string area2 = "Ganesh Chandra Avenue";

        //checking and printing the result
        if (address.Contains(area1))
        {
            Console.WriteLine(area1 + " exists in the address " + address);
        }
        else
        {
            Console.WriteLine(area1 + " does not exist in the address " + address);
        }

        if (address.Contains(area2))
        {
            Console.WriteLine(area2 + " exists in the address " + address);
        }
        else
        {
            Console.WriteLine(area2 + " does not exist in the address " + address);
        }
    }
}

Output:

MD Computers exists in the address 16/1 Ganesh Chandra Avenue, Kolkata 700013, India.
Sunrise Apt. does not exist in the address 16/1 Ganesh Chandra Avenue, Kolkata 700013, India.

Leave a Comment

error: Alert: Content is protected!!