w3resource

C#: Check whether a given substring is present in the given string

C# Sharp String: Exercise-14 with Solution

Write a C# Sharp program to check whether a given substring is present in the given string

C# Sharp Exercises: Check whether a given substring is present in the given string.

Sample Solution:-

C# Sharp Code:

using System;

// Define the exercise14 class
public class exercise14
{
    // Main method - entry point of the program
    public static void Main()
    {
        string str1, str2; // Declare two string variables to store input
        bool m; // Declare a boolean variable to store the result of substring search

        // Prompt the user for input
        Console.Write("\n\nCheck whether a given substring is present in the given string :\n");
        Console.Write("-------------------------------------------------------------------\n");
        Console.Write("Input the string : ");
        str1 = Console.ReadLine(); // Read the input string from the user

        Console.Write("Input the substring to search : ");
        str2 = Console.ReadLine(); // Read the substring to search from the user

        m = str1.Contains(str2); // Check if str1 contains str2, stores the result in boolean variable 'm'

        // Check if the substring exists in the string and output the result
        if (m) // If 'm' is true, the substring exists in the string
            Console.Write("The substring exists in the string.\n\n");
        else // If 'm' is false, the substring does not exist in the string
            Console.Write("The substring does not exist in the string.\n\n");
    }
}

Sample Output:

Check whether a given  substring is present in the given strig :       
-------------------------------------------------------------------    
Input the string : Welcome to w3resource.com                           
Input the substring to  search : w3resource                            
The substring exists in the string.

Flowchart:

Flowchart: Check whether a given substring is present in the given strig

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to extract a substring from a given string without using the library function.
Next: Write a program in C# Sharp to read a sentence and replace lowercase characters by uppercase and vice-versa.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/string/csharp-string-exercise-14.php