簡體   English   中英

如何檢查字符串是否包含某些字符串

[英]How to check if a String contains any of some strings

我想檢查 C# 中的 String 是否包含“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");

沒有什么能與您的||鏈的性能相匹配比較,不過。

這是一個幾乎相同但更具可擴展性的 LINQ 解決方案:

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

如果您正在尋找單個字符,您可以使用String.IndexOfAny()

如果你想要任意字符串,那么我不知道有一種 .NET 方法可以“直接”實現,盡管正則表達式可以工作。

您可以嘗試使用正則表達式

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

如果您需要具有特定StringComparison ContainsAny(例如忽略大小寫),則可以使用此 String Extentions 方法。

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.

這是一個“更好的解決方案”而且非常簡單

if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))
List<string> includedWords = new List<string>() { "a", "b", "c" };
bool string_contains_words = includedWords.Exists(o => s.Contains(o));
public static bool ContainsAny(this string haystack, IEnumerable<string> needles)
{
    return needles.Any(haystack.Contains);
}

由於字符串是字符的集合,您可以對它們使用 LINQ 擴展方法:

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

這將掃描字符串一次並在第一次出現時停止,而不是為每個字符掃描一次字符串直到找到匹配項。

這也可以用於您喜歡的任何表達式,例如檢查字符范圍:

if (s.Any(c => c >= 'a' && c <= 'c')) ...
// 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 for any, All for each

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

您可以使用正則表達式

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

你可以為你的擴展方法創建一個類並添加這個類:

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

如果您要查找任意字符串,而不僅僅是字符,則可以使用IndexOfAny的重載,該重載從新項目NLib中獲取字符串參數:

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

如果這是用於有要求的密碼檢查器,請嘗試以下操作:

public static bool PasswordChecker(string input)
{
    // determins if a password is save enough
    if (input.Length < 8)
        return false;

    if (!new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                        "S", "T", "U", "V", "W", "X", "Y", "Z", "Ä", "Ü", "Ö"}.Any(s => input.Contains(s)))
    return false;

    if (!new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}.Any(s => input.Contains(s)))
    return false;

    if (!new string[] { "!", "'", "§", "$", "%", "&", "/", "(", ")", "=", "?", "*", "#", "+", "-", "_", ".",
                        ",", ";", ":", "`", "´", "^", "°",   }.Any(s => input.Contains(s)))
    return false;

    return true; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM