如何检查String是否包含任何字符串

时间:2010-08-19 07:11:03

标签: c#

我想在C#中检查String是否包含“a”或“b”或“c”。 我正在寻找比使用

更好的解决方案
if (s.contains("a")||s.contains("b")||s.contains("c"))

15 个答案:

答案 0 :(得分:78)

嗯,总是这样:

public static bool ContainsAny(this string haystack, params string[] needles)
{
    foreach (string needle in needles)
    {
        if (haystack.Contains(needle))
            return true;
    }

    return false;
}

用法:

bool anyLuck = s.ContainsAny("a", "b", "c");

然而,没有任何东西能与您的||比较链的性能相匹配。

答案 1 :(得分:51)

这是一个LINQ解决方案,几乎相同但可扩展性更强:

new[] { "a", "b", "c" }.Any(c => s.Contains(c))

答案 2 :(得分:39)

如果您要查找单个字符,可以使用String.IndexOfAny()

如果你想要任意字符串,那么我不知道有一种.NET方法可以“直接”实现,尽管正则表达式可以工作。

答案 3 :(得分:33)

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);

答案 4 :(得分:21)

您可以尝试使用正则表达式

string s;
Regex r = new Regex ("a|b|c");
bool containsAny = r.IsMatch (s);

答案 5 :(得分:8)

如果您需要具有特定StringComparison的ContainsAny(例如忽略大小写),则可以使用此字符串扩展方法。

public static class StringExtensions
{
    public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
    {
        return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
    }
}

使用StringComparison.CurrentCultureIgnoreCase

var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.

”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.

答案 6 :(得分:6)

这是一个“更好的解决方案”而且非常简单

if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))

答案 7 :(得分:4)

由于字符串是一组字符,因此可以对它们使用LINQ扩展方法:

if (s.Any(c => c == 'a' || c == 'b' || c == 'c')) ...

这将扫描字符串一次并在第一次出现时停止,而不是为每个字符扫描一次字符串,直到找到匹配为止。

这也可用于您喜欢的任何表达式,例如检查一系列字符:

if (s.Any(c => c >= 'a' && c <= 'c')) ...

答案 8 :(得分:3)

public static bool ContainsAny(this string haystack, IEnumerable<string> needles)
{
    return needles.Any(haystack.Contains);
}

答案 9 :(得分:2)

// Nice method's name, @Dan Tao

public static bool ContainsAny(this string value, params string[] params)
{
    return params.Any(p => value.Compare(p) > 0);
    // or
    return params.Any(p => value.Contains(p));
}

Any代表任何All代表

答案 10 :(得分:2)

List<string> includedWords = new List<string>() { "a", "b", "c" };
bool string_contains_words = includedWords.Exists(o => s.Contains(o));

答案 11 :(得分:2)

    static void Main(string[] args)
    {
        string illegalCharacters = "!@#$%^&*()\\/{}|<>,.~`?"; //We'll call these the bad guys
        string goodUserName = "John Wesson";                   //This is a good guy. We know it. We can see it!
                                                               //But what if we want the program to make sure?
        string badUserName = "*_Wesson*_John!?";                //We can see this has one of the bad guys. Underscores not restricted.

        Console.WriteLine("goodUserName " + goodUserName +
            (!HasWantedCharacters(goodUserName, illegalCharacters) ?
            " contains no illegal characters and is valid" :      //This line is the expected result
            " contains one or more illegal characters and is invalid"));
        string captured = "";
        Console.WriteLine("badUserName " + badUserName +
            (!HasWantedCharacters(badUserName, illegalCharacters, out captured) ?
            " contains no illegal characters and is valid" :
            //We can expect this line to print and show us the bad ones
            " is invalid and contains the following illegal characters: " + captured));  

    }

    //Takes a string to check for the presence of one or more of the wanted characters within a string
    //As soon as one of the wanted characters is encountered, return true
    //This is useful if a character is required, but NOT if a specific frequency is needed
    //ie. you wouldn't use this to validate an email address
    //but could use it to make sure a username is only alphanumeric
    static bool HasWantedCharacters(string source, string wantedCharacters)
    {
        foreach(char s in source) //One by one, loop through the characters in source
        {
            foreach(char c in wantedCharacters) //One by one, loop through the wanted characters
            {
                if (c == s)  //Is the current illegalChar here in the string?
                    return true;
            }
        }
        return false;
    }

    //Overloaded version of HasWantedCharacters
    //Checks to see if any one of the wantedCharacters is contained within the source string
    //string source ~ String to test
    //string wantedCharacters ~ string of characters to check for
    static bool HasWantedCharacters(string source, string wantedCharacters, out string capturedCharacters)
    {
        capturedCharacters = ""; //Haven't found any wanted characters yet

        foreach(char s in source)
        {
            foreach(char c in wantedCharacters) //Is the current illegalChar here in the string?
            {
                if(c == s)
                {
                    if(!capturedCharacters.Contains(c.ToString()))
                        capturedCharacters += c.ToString();  //Send these characters to whoever's asking
                }
            }
        }

        if (capturedCharacters.Length > 0)  
            return true;
        else
            return false;
    }

答案 12 :(得分:1)

您可以使用Regular Expressions

if(System.Text.RegularExpressions.IsMatch("a|b|c"))

答案 13 :(得分:1)

你可以为你的扩展方法创建一个类并添加这个:

    public static bool Contains<T>(this string s, List<T> list)
    {
        foreach (char c in s)
        {
            foreach (T value in list)
            {
                if (c == Convert.ToChar(value))
                    return true;
            }
        }
        return false;
    }

答案 14 :(得分:0)

如果您正在寻找任意字符串,而不仅仅是字符,您可以使用IndexOfAny的重载,该重载从新项目NLib获取字符串参数:

if (s.IndexOfAny("aaa", "bbb", "ccc", StringComparison.Ordinal) >= 0)