C#: 2 Ways to Check if a String contains another String

Last updated on September 20, 2021 Napoleon Loading... Post a comment

This short and straight-to-the-point article shows you two different ways to whether a string contains another string in C Sharp. The first approach is case SENSITIVE while the second one is case INSENSITIVE.

Using the Contains() method (case sensitive)

Example:

using System;
					
public class Program
{
	public static void Main()
	{
		String s1 = "ABCDEF";
		String s2 = "abc";
		String s3 = "ABC";
		
		if(s1.Contains(s2)){
			Console.WriteLine("S1 contains s2");
		} else {
			Console.WriteLine("S1 does NOT contains s2");
		}
		
		if(s1.Contains(s3)){
			Console.WriteLine("S1 contains s3");
		} else {
			Console.WriteLine("S1 does NOT contains s3");
		}
	}
}

Output:

S1 does NOT contains s2
S1 contains s3

Using the IndexOf() method (case insensitive)

Example:

using System;
					
public class Program
{
	public static void Main()
	{
		String s1 = "ABCDEF";
		String s2 = "abc";
		
		if(s1.IndexOf(s2, StringComparison.OrdinalIgnoreCase) >= 0){
			Console.WriteLine("S1 contains s2");
		} else {
			Console.WriteLine("S1 does NOT contains s2");
		}
	}
}

Output:

S1 contains s2

That’s it. Happy coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like