How To Check If String Contains Specified Substring In C#?
Maybe your like
C# Check if String contains Specified Substring
To check if a string str contains specified substring value, or say if specified substring is present in the string, use C# String.Contains(String) method.
Call Contains() method on the string str and pass the substring value as argument. Contains() method returns True if string str contains the substring value.
Examples
1. Check if string contains the substring ‘cd’
In the following program, we take a string in str, and a search string in value, and check if the string str contains the string value as a substring.
C# Program
</> Copy using System; class Example { static void Main(string[] args) { String str = "abcdefgh"; String value = "cd"; Boolean result = str.Contains(value); Console.WriteLine($"Does string contain specified substring? {result}"); } }Output
Does string contain specified substring? True2. Check if string contains substring ‘mno’
In this example, we have taken the string value and search string value, such that the search string is not present in the string as a substring.
If substring value is not present in this string str, then Contains() method returns False.
C# Program
</> Copy using System; class Example { static void Main(string[] args) { String str = "abcdefgh"; String value = "mno"; Boolean result = str.Contains(value); Console.WriteLine($"Does string contain specified substring? {result}"); } }Output
Does string contain specified substring? False3. Check if string contains substring ‘CD’, ignoring the case
If we would like to ignore case while checking if the substring is present in the string, you may specify to ignore case via StringComparison object as shown in the following example.
C# Program
</> Copy using System; class Example { static void Main(string[] args) { String str = "abcdefgh"; String value = "CD"; StringComparison comp = StringComparison.OrdinalIgnoreCase; Boolean result = str.Contains(value, comp); Console.WriteLine($"Does string contain specified substring? {result}"); } }Output
Does string contain specified substring? TrueConclusion
In this C# Tutorial, we learned how to check if specified substring is present in a given string.
Tag » What Is Substring In C#
-
Substring In C# - C# Corner
-
C# | Substring() Method - GeeksforGeeks
-
String.Substring Method (System) | Microsoft Learn
-
C# String Substring() (With Examples) - Programiz
-
C# Substring() Method - Tutorialspoint
-
How To Use C# String Substring
-
C# Substring Examples - Dot Net Perls
-
C# Substring 문자열 자르기 - 개발인생
-
How To Get A Substring From A String In C#
-
C# String SubString() Method - Javatpoint
-
082 - How To Use C# String Substring - YouTube
-
What Is Substring In C# With Example? [60 Answers Found]
-
Visual C# .net Strings - Substring - Home And Learn Courses
-
JavaScript String Substring() Method - W3Schools