Answers:
正如其他人所说,请使用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;
}
ToCharArray
当然,如果需要,您可以使用“内联”形式。
如果您只想查看它是否包含任何字符,我建议使用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;
}
String.IndexOfAny(Char[])
这是Microsoft的文档。
感谢大家!(主要是乔恩!):这让我可以这样写:
private static readonly char[] Punctuation = "$€£".ToCharArray();
public static bool IsPrice(this string text)
{
return text.IndexOfAny(Punctuation) >= 0;
}
因为我在寻找一种检测特定字符串实际上是价格还是句子的好方法,例如“显示得太低”。