Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to check if a Substring is present in a Given String
The Contains() method in C# is used to check if a substring is present within a given string. It returns a boolean value − true if the substring is found, and false otherwise.
Syntax
Following is the syntax for the Contains() method −
bool result = string.Contains(substring);
Parameters
-
substring − The string to search for within the main string.
Return Value
The Contains()bool value −
-
true− if the substring is found in the main string -
false− if the substring is not found
Using Contains() Method
Example 1: Basic Substring Check
The following example demonstrates how to check if "Uni" is present in the string "United" −
using System;
public class Demo {
public static void Main() {
string str1 = "United", str2 = "Uni";
bool res;
res = str1.Contains(str2);
if (res)
Console.WriteLine("The substring '" + str2 + "' is in the string '" + str1 + "'");
else
Console.WriteLine("The substring '" + str2 + "' is not in the string '" + str1 + "'");
}
}
The output of the above code is −
The substring 'Uni' is in the string 'United'
Example 2: Case-Sensitive Search
The Contains() method is case-sensitive by default −
using System;
public class CaseSensitiveDemo {
public static void Main() {
string mainString = "Programming";
string substring1 = "gram";
string substring2 = "GRAM";
Console.WriteLine("Main string: " + mainString);
Console.WriteLine("Searching for 'gram': " + mainString.Contains(substring1));
Console.WriteLine("Searching for 'GRAM': " + mainString.Contains(substring2));
}
}
The output of the above code is −
Main string: Programming Searching for 'gram': True Searching for 'GRAM': False
Example 3: Case-Insensitive Search
For case-insensitive searches, use the StringComparison.OrdinalIgnoreCase parameter −
using System;
public class CaseInsensitiveDemo {
public static void Main() {
string mainString = "Programming";
string substring = "GRAM";
bool caseSensitive = mainString.Contains(substring);
bool caseInsensitive = mainString.Contains(substring, StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Main string: " + mainString);
Console.WriteLine("Case-sensitive search for 'GRAM': " + caseSensitive);
Console.WriteLine("Case-insensitive search for 'GRAM': " + caseInsensitive);
}
}
The output of the above code is −
Main string: Programming Case-sensitive search for 'GRAM': False Case-insensitive search for 'GRAM': True
Conclusion
The Contains() method provides a simple and efficient way to check if a substring exists within a string in C#. Remember that it is case-sensitive by default, but you can perform case-insensitive searches using the StringComparison.OrdinalIgnoreCase parameter.
