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

Jad*_*e M 98 c# string

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

什么是最好的方法?

Nol*_*rin 197

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

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

或者以一种可能更容易阅读的形式:

var match = str.IndexOfAny("*&#".ToCharArray()) != -1
Run Code Online (Sandbox Code Playgroud)

根据所需的上下文和性能,您可能想要或不想要缓存char数组.


Jon*_*eet 38

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

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

public static bool ContainsPunctuation(string text)
{
    return text.IndexOfAny(Punctuation) >= 0;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

public static bool ContainsPunctuation(string text)
{
    return text.IndexOfAny(Punctuation.ToCharArray()) >= 0;
}
Run Code Online (Sandbox Code Playgroud)

要么

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

这取决于你发现哪些更具可读性,是否要在其他地方使用标点符号,以及调用该方法的频率.


编辑:这是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;
}
Run Code Online (Sandbox Code Playgroud)


Ree*_*sey 5

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

如果你想验证字符串包含只有一个的十个字符,只有一个,那问题就变得更复杂一些.我认为最快的方法是检查交叉点,然后检查重复项.

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;
}
Run Code Online (Sandbox Code Playgroud)