How can I check if a string contains a character i

2020-01-29 03:49发布

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# string
8条回答
别忘想泡老子
2楼-- · 2020-01-29 04:24

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"))
        { 
            //...
        }
查看更多
虎瘦雄心在
3楼-- · 2020-01-29 04:32

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");
    }
}
查看更多
登录 后发表回答