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

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

最好的办法是什么?

109789 次浏览
String.IndexOfAny(Char[])

这里是 微软的文档

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

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

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

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

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

正如其他人所说,使用 IndexOfAny. 然而,我会这样使用它:

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


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

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

当然,如果你只打算使用一次,所以浪费的创造不是问题,你可以使用:

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


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

或者

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

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


编辑: 这里是 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;
}

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

如果您想要验证一个字符串是否包含十个字符的 exactly one,并且只有一个字符,那么它会变得稍微复杂一些。我认为最快的方法是在十字路口进行检查,然后检查是否有副本。

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


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

感谢你们所有人! (主要是乔恩!) : 这让我可以这样写:

    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'.