C# 检查字符串是否包含 10 个字符之一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1390749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:58:39  来源:igfitidea点击:

Check if a string contains one of 10 characters

c#string

提问by Jade M

I'm using C# and I want to check if a string contains one of ten characters, *, &, # etc etc.

我正在使用 C#,我想检查一个字符串是否包含十个字符之一,*、&、# 等。

What is the best way?

什么是最好的方法?

采纳答案by Noldorin

The following would be the simplest method, in my view:

在我看来,以下是最简单的方法:

var match = str.IndexOfAny(new char[] { '*', '&', '#' }) != -1

Or in a possibly easier to read form:

或者以更容易阅读的形式:

var match = str.IndexOfAny("*&#".ToCharArray()) != -1

Depending on the context and performance required, you may or may not want to cache the char array.

根据所需的上下文和性能,您可能希望也可能不想缓存字符数组。

回答by Jason Williams

String.IndexOfAny(Char[])

Here is the Microsoft's documentation.

这是微软的文档

回答by Jon Skeet

As others have said, use IndexOfAny. However, I'd use it in this way:

正如其他人所说,使用 IndexOfAny。但是,我会以这种方式使用它:

private static readonly char[] Punctuation = "*&#...".ToCharArray();

public static bool ContainsPunctuation(string text)
{
    return text.IndexOfAny(Punctuation) >= 0;
}

That way you don't end up creating a new array on each call. The string is also easier to scan than a series of character literals, IMO.

这样你就不会在每次调用时都创建一个新数组。该字符串也比一系列字符文字更容易扫描,IMO。

Of course if you're only going to use this once, so the wasted creation isn't a problem, you could either use:

当然,如果您只打算使用一次,那么浪费的创建不是问题,您可以使用:

private const string Punctuation = "*&#...";

public static bool ContainsPunctuation(string text)
{
    return text.IndexOfAny(Punctuation.ToCharArray()) >= 0;
}

or

或者

public static bool ContainsPunctuation(string text)
{
    return text.IndexOfAny("*&#...".ToCharArray()) >= 0;
}

It really depends on which you find more readable, whether you want to use the punctuation characters elsewhere, and how often the method is going to be called.

这实际上取决于您认为哪个更具可读性,您是否想在其他地方使用标点符号,以及调用该方法的频率。



EDIT: Here's an alternative to Reed Copsey's method for finding out if a string contains exactly oneof the characters.

编辑:这里有一种替代 Reed Copsey 的方法,用于确定字符串是否恰好包含一个字符。

private static readonly HashSet<char> Punctuation = new HashSet<char>("*&#...");

public static bool ContainsOnePunctuationMark(string text)
{
    bool seenOne = false;

    foreach (char c in text)
    {
        // TODO: Experiment to see whether HashSet is really faster than
        // Array.Contains. If all the punctuation is ASCII, there are other
        // alternatives...
        if (Punctuation.Contains(c))
        {
            if (seenOne)
            {
                return false; // This is the second punctuation character
            }
            seenOne = true;
        }
    }
    return seenOne;
}

回答by Reed Copsey

If you just want to see if it contains any character, I'd recommend using string.IndexOfAny, as suggested elsewhere.

如果您只想查看它是否包含任何字符,我建议使用 string.IndexOfAny,正如其他地方所建议的那样。

If you want to verify that a string contains exactly oneof the ten characters, and only one, then it gets a bit more complicated. I believe the fastest way would be to check against an Intersection, then check for duplicates.

如果你想验证字符串包含只有一个的十个字符,只有一个,那么它变得有点复杂。我相信最快的方法是检查一个交叉点,然后检查重复项。

private static char[] characters = new char [] { '*','&',... };

public static bool ContainsOneCharacter(string text)
{
    var intersection = text.Intersect(characters).ToList();
    if( intersection.Count != 1)
        return false; // Make sure there is only one character in the text

    // Get a count of all of the one found character
    if (1 == text.Count(t => t == intersection[0]) )
        return true;

    return false;
}

回答by nologo

var specialChars = new[] {'\', '/', ':', '*', '<', '>', '|', '#', '{', '}', '%', '~', '&'};

foreach (var specialChar in specialChars.Where(str.Contains))
{
    Console.Write(string.Format("string must not contain {0}", specialChar));
}

回答by BernardG

Thanks to all of you! (And Mainly Jon!): This allowed me to write this:

感谢大家!(主要是 Jon!):这让我可以这样写:

    private static readonly char[] Punctuation = "$£".ToCharArray();

    public static bool IsPrice(this string text)
    {
        return text.IndexOfAny(Punctuation) >= 0;
    }

as I was searching for a good way to detect if a certain string was actually a price or a sentence, like 'Too low to display'.

因为我正在寻找一种好方法来检测某个字符串实际上是价格还是句子,例如“太低而无法显示”。