如何检查一个字符串是否包含任何一些字符串

问题描述:

我想检查一个字符串是否包含“a”或“b”或“c”,在C#中。 我要寻找一个更好的解决方案比使用如何检查一个字符串是否包含任何一些字符串

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

对于复杂的情况下查找'trie'数据结构。 – 2013-10-22 21:18:47

如果您正在寻找单个字符,你可以使用String.IndexOfAny()

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

嘛,总是有这样的:

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

+1的通用解决方案 – Stavros 2010-08-19 07:27:47

+3

添加新的短语法这个很好的解决方案 '公共静态布尔ContainsAny(这个字符串大海捞针,则params字符串[]针) { 回报needles.Any(haystack.Contains); }' – simonkaspers1 2017-05-05 08:17:44

你可以用正则表达式

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

+1,但是因为他正在寻找单个字符,所以linq解决方案或indexOfAny可能更有效。 – 2010-08-19 07:15:49

+0

正则表达式的+1。这就是我会去的,如果没有IndexOfAny – Stavros 2010-08-19 07:29:25

+1

正则表达式对此是矫枉过正。 – 2010-08-19 07:32:26

尝试你可以使用Regular Expressions

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

你当然可以,但我不明白为什么你会想要什么时候什么都好些。 – 2010-08-19 07:55:27

这里的LINQ解决方案,它几乎是相同的,但更多的可扩展性:

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

这是可扩展的,因为它很容易添加字符,而不是性能意义上的...... :) – Guffa 2010-08-19 07:31:56

+1

啊,当然是。也许“更具可扩展性”是更好的选择。 – 2010-08-19 07:39:51

+0

表演不会太糟糕。无论如何,优于解释的正则表达式。 – 2010-08-19 07:53:58

作为字符串是字符的集合,你可以对它们使用LINQ扩展方法:

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

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

这也可以被用于任何你喜欢的表情,例如用于字符范围检查:

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

同意。这解决了第一个条件不匹配时多次扫描的问题。不知道lambda的开销是多少?不应该多一次,虽然。 – bruceboughton 2010-08-19 08:57:00

// 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为每

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

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

该链接不再有效。 – 2017-07-25 06:10:11

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

带上我的标记它的工作原理... – Steve 2015-06-11 13:17:16

这是一个“更好的解决方案”,并很简单

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

用法与StringComparison.CurrentCultureIgnoreCase

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

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

只是一个音符来改善这个答案。你可以写它更与params关键字ellegant: ContainsAny(这个字符串输入,StringComparison comparisonType,则params字符串[] containsKeywords) 和使用像 input.ContainsAny(子,StringComparison.CurrentCultureIgnoreCase, “串”, “多个子串”...等) – 2017-01-08 16:20:48

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 = "[email protected]#$%^&*()\\/{}|<>,.~`?"; //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; 
    } 
+0

你能解释一下你的代码吗 – 2017-09-23 21:00:50

+1

HasWantedCharacters方法接受两个或三个字符串。我们想要检查某些字符的第一个字符串。第二个字符串,我们将在第一个字符中找到的所有字符。重载的方法为第三个字符串提供输出给调用者(即Main)。嵌套的foreach语句会遍历源文件中的每个字符并逐个比较它;与我们正在检查的那些角色。如果找到其中一个字符,则返回true。重载的方法输出一串符合检查匹配的字符,但直到所有字符都熄灭才会返回。有用吗? – 2017-09-23 21:54:09

+1

随意启动C#控制台项目并将代码复制到程序类中 - 请务必替换主要方法。修改两个字符串(goodUserName和badUserName),你可能会看到这些方法做了什么以及它们是如何工作的。这些例子比较长,以便提供一个可行的解决方案,可以在没有分隔符(如逗号)的情况下进行修改。如果您需要检查它们,转义序列只是表示单引号和反斜线的一种方式。 – 2017-09-23 22:04:53