C# 如何检查字符串是否包含某些字符串中的任何一个

C# 如何检查字符串是否包含某些字符串中的任何一个,c#,C#,我想检查字符串s在c#中是否包含“a”或“b”或“c”。 我正在寻找一个比使用 if (s.contains("a")||s.contains("b")||s.contains("c")) 嗯,总是有这样的情况: public static bool ContainsAny(this string haystack, params string[] needles) { foreach (string needle in needles) { if (hayst

我想检查字符串s在c#中是否包含“a”或“b”或“c”。 我正在寻找一个比使用

if (s.contains("a")||s.contains("b")||s.contains("c"))

嗯,总是有这样的情况:

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

但是,没有任何东西可以与您的
|
比较链的性能相匹配。

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

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


如果要查找单个字符,可以使用


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

这里有一个LINQ解决方案,它实际上是相同的,但更具可扩展性:

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

由于字符串是字符的集合,因此可以对其使用LINQ扩展方法:

if (s.Any(c => c == 'a' || c == 'b' || c == 'c')) ...
这将扫描字符串一次并在第一次出现时停止,而不是对每个字符扫描字符串一次,直到找到匹配项

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

if (s.Any(c => c >= 'a' && c <= 'c')) ...
if(s.Any)(c=>c>='a'&&c
Any
对于Any,
All
对于every

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

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);
if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))

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

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);
    }
}
publicstaticboolcontainsany(这个字符串是干草堆,IEnumerable针)
{
返回针。任何(haystack.Contains);
}
List includewords=newlist(){“a”、“b”、“c”};
bool string_contains_words=includedWords.Exists(o=>s.contains(o));
静态void Main(字符串[]args)
{
string illegalCharacters=“!@\\$%^&*()\\/{}124;,.~`?”;//我们称之为坏人
string goodUserName=“John Wesson”//这是个好人。我们知道。我们可以看到!
//但是如果我们想让这个项目确定呢?
string badUserName=“*\u Wesson*\u John!?”;//我们可以看到这有一个坏人。下划线不受限制。
Console.WriteLine(“goodUserName”+goodUserName+
(!HasWantedCharacters(goodUserName,非法字符)?
“不包含非法字符且有效”://此行是预期结果
“包含一个或多个非法字符,无效”);
字符串“”被捕获;
Console.WriteLine(“badUserName”+badUserName+
(!HasWantedCharacters(坏用户名、非法字符、捕获外字符)?
“不包含非法字符且有效:”
//我们可以期待这一行打印出来,并告诉我们坏的
无效且包含以下非法字符:“+captured”);
}
//获取字符串以检查字符串中是否存在一个或多个所需字符
//一旦遇到所需的字符之一,就返回true
//如果需要一个字符,这是有用的,但如果需要特定的频率,则不可用
//你不会用这个来验证一个电子邮件地址
//但可以使用它来确保用户名仅为字母数字
静态bool HasWantedCharacters(字符串源、字符串wantedCharacters)
{
foreach(源代码中的字符)//逐个循环源代码中的字符
{
foreach(wantedCharacters中的char c)//逐个循环遍历所需的字符
{
if(c==s)//字符串中是否有当前的非法字符?
返回true;
}
}
返回false;
}
//HasWantedCharacters的重载版本
//检查源字符串中是否包含任何wantedCharacters
//字符串源~要测试的字符串
//string wantedCharacters~要检查的字符串
静态bool HasWantedCharacters(字符串源、字符串wantedCharacters、输出字符串capturedCharacters)
{
capturedCharacters=“”;//尚未找到任何想要的角色
foreach(源中的字符)
{
foreach(字符c在wantedCharacters中)//当前的非法字符是否在字符串中?
{
如果(c==s)
{
如果(!capturedCharacters.Contains(c.ToString()))
capturedCharacters+=c.ToString();//将这些字符发送给任何询问的人
}
}
}
如果(capturedCharacters.Length>0)
返回true;
其他的
返回false;
}

+1,因为他在寻找单字符,linq解决方案或indexOfAny可能更有效。+1用于正则表达式。如果没有IndexOfAnyRegular表达式,我会这么做的。为什么人们会说正则表达式在这方面做得过火了?如果正则表达式编译一次并使用多个IME,如果字符串中只有c,或者靠近开头的是c,靠近结尾的是a,b,那么正则表达式的效率会更高。它不适用于像-,“```=这样的特殊字符,它是可伸缩的,因为它很容易添加字符,而不是在性能上……:)啊,是的,当然。也许“更可扩展”“会是一个更好的词语选择。性能不会很差。无论如何,比解释的regexp要好。非常棒的答案只是为了完整性,您可以先将传入字符串拆分为一个数组,例如:var splitStringArray=someString.split(“”);然后您可以执行以下操作:if(someStringArray.Any)(s=>otherString.Contains(s)){//do something}希望这有助于澄清。你当然可以,但我不明白你为什么要在几乎所有其他条件都更好的情况下这样做。同意。这解决了第一个条件不匹配时多次扫描的问题。想知道lambda的开销是什么吗?应该不会太大。对于复杂的情况,请查找
trie
d
if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))
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);
    }
}
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.
public static bool ContainsAny(this string haystack, IEnumerable<string> needles)
{
    return needles.Any(haystack.Contains);
}
List<string> includedWords = new List<string>() { "a", "b", "c" };
bool string_contains_words = includedWords.Exists(o => s.Contains(o));
    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;
    }