[c#] How can I check if a string contains a character in C#?

Is there a function I can apply to a string that will return true of false if a string contains a character.

I have strings with one or more character options such as:

var abc = "s";
var def = "aB";
var ghi = "Sj";

What I would like to do for example is have a function that would return true or false if the above contained a lower or upper case "s".

if (def.Somefunction("s") == true) { }

Also in C# do I need to check if something is true like this or could I just remove the "== true" ?

This question is related to c# string

The answer is


It will be hard to work in C# without knowing how to work with strings and booleans. But anyway:

        String str = "ABC";
        if (str.Contains('A'))
        { 
            //...
        }

        if (str.Contains("AB"))
        { 
            //...
        }

Use the function String.Contains();

an example call,

abs.Contains("s"); // to look for lower case s

here is more from MSDN.


The following should work:

var abc = "sAb";
bool exists = abc.IndexOf("ab", StringComparison.CurrentCultureIgnoreCase) > -1;

You can create your own extention method if you plan to use this a lot.

public static class StringExt
{
    public static bool ContainsInvariant(this string sourceString, string filter)
    {
        return sourceString.ToLowerInvariant().Contains(filter);
    }
}

example usage:

public class test
{
    public bool Foo()
    {
        const string def = "aB";
        return def.ContainsInvariant("s");
    }
}

bool containsCharacter = test.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0;

You can use the IndexOf method, which has a suitable overload for string comparison types:

if (def.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0) ...

Also, you would not need the == true, since an if statement only expects an expression that evaluates to a bool.


here is an example what most of have done

using System;

class Program
{
    static void Main()
    {
        Test("Dot Net Perls");
        Test("dot net perls");
    }

    static void Test(string input)
    {
        Console.Write("--- ");
        Console.Write(input);
        Console.WriteLine(" ---");
        //
        // See if the string contains 'Net'
        //
        bool contains = input.Contains("Net");
        //
        // Write the result
        //
        Console.Write("Contains 'Net': ");
        Console.WriteLine(contains);
        //
        // See if the string contains 'perls' lowercase
        //
        if (input.Contains("perls"))
        {
            Console.WriteLine("Contains 'perls'");
        }
        //
        // See if the string contains 'Dot'
        //
        if (!input.Contains("Dot"))
        {
            Console.WriteLine("Doesn't Contain 'Dot'");
        }
    }
}