Подтвердить что ты не робот

Как проверить, содержит ли строка какие-либо строки

Я хочу проверить, содержит ли строка S, содержащую "a" или "b" или "c", в С#. Я ищу более приятное решение, чем использование

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

Ответ 1

Если вы ищете одиночные символы, вы можете использовать String.IndexOfAny().

Если вам нужны произвольные строки, то я не знаю о методе .NET для достижения этого "прямо", хотя регулярное выражение будет работать.

Ответ 2

Ну, всегда это:

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

Тем не менее, ничего не сравнится с производительностью вашей цепочки сравнений ||.

Ответ 3

Здесь решение LINQ, которое практически одно и то же, но более масштабируемое:

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

Ответ 4

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

Ответ 5

Вы можете попробовать с регулярным выражением

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

Ответ 6

Если вам нужен ContainsAny с определенным StringComparison (например, чтобы игнорировать регистр), то вы можете использовать этот метод 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.

Ответ 7

Это "лучшее решение" и довольно простая

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

Ответ 8

Поскольку строка представляет собой набор символов, вы можете использовать методы расширения LINQ для них:

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

Это сканирует строку один раз и останавливается при первом возникновении, вместо того, чтобы сканировать строку один раз для каждого символа до тех пор, пока не будет найдено совпадение.

Это также можно использовать для любого выражения, которое вам нравится, например, для проверки диапазона символов:

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

Ответ 9

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

Ответ 10

// Nice method 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 для каждого

Ответ 11

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

Ответ 12

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

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

Ответ 14

Если вы ищете произвольные строки, а не только символы, вы можете использовать перегрузку IndexOfAny, которая принимает строковые аргументы из нового проекта NLib:

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