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

C#String

C# Problem Overview


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" ?

C# Solutions


Solution 1 - C#

You can use the extension method .Contains() from the namespace System.Linq:

using System.Linq;

    ...

    if (abc.ToLower().Contains('s')) { }

And also, to check if a boolean expression is true, you don't need == true

Since the Contains method is an extension method, my solution might be confusing. Here are two versions that don't require you to add using System.Linq;:

if (abc.ToLower().IndexOf('s') != -1) { }

// or:

if (abc.IndexOf("s", StringComparison.CurrentCultureIgnoreCase) != -1) { }

Update

If you want to, you can write your own extensions method for easier reuse:

public static class MyStringExtensions
{
    public static bool ContainsAnyCaseInvariant(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) != -1;
    }
    
    public static bool ContainsAnyCase(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.CurrentCultureIgnoreCase) != -1;
    }
}

Then you can call them like this:

if (def.ContainsAnyCaseInvariant('s')) { }
// or
if (def.ContainsAnyCase('s')) { }

In most cases when dealing with user data, you actually want to use CurrentCultureIgnoreCase (or the ContainsAnyCase extension method), because that way you let the system handle upper/lowercase issues, which depend on the language. When dealing with computational issues, like names of HTML tags and so on, you want to use the invariant culture.

For example: In Turkish, the uppercase letter I in lowercase is ı (without a dot), and not i (with a dot).

Solution 2 - C#

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.

Solution 3 - C#

Use the function String.Contains();

an example call,

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

here is more from MSDN.

Solution 4 - C#

The following should work:

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

Solution 5 - C#

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

Solution 6 - C#

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"))
        { 
            //...
        }

Solution 7 - C#

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");
    }
}

Solution 8 - C#

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'");
        }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamantha J T StarView Question on Stackoverflow
Solution 1 - C#Anders Marzi TornbladView Answer on Stackoverflow
Solution 2 - C#Rich O'KellyView Answer on Stackoverflow
Solution 3 - C#Shamim Hafiz - MSFTView Answer on Stackoverflow
Solution 4 - C#tobias86View Answer on Stackoverflow
Solution 5 - C#bniwredycView Answer on Stackoverflow
Solution 6 - C#SergejsView Answer on Stackoverflow
Solution 7 - C#MyrtleView Answer on Stackoverflow
Solution 8 - C#Karan ShahView Answer on Stackoverflow