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

后端 未结 8 977
陌清茗
陌清茗 2020-12-02 09:43

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

8条回答
  •  [愿得一人]
    2020-12-02 10:21

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

    using System.Linq;
    
        ...
    
        if (abc.ToLower().Contains('s')) { }
    

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

    Since the Contains method is an extension method, my solution appeared to be confusing to some. 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).

提交回复
热议问题