我正在使用C#,想要检查一个字符串是否包含十个字符之一,如*、&、#等等。
最好的方法是什么?
最好的方法是什么?
以下是我认为最简单的方法:
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;
}
这样,您就不会在每次调用时创建一个新数组。在我看来,与一系列字符字面量相比,字符串的扫描也更容易。
当然,如果您只打算使用一次,那么浪费的创建并不是问题,您可以使用:
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
形式。 - Jon Skeet如果您只想查看字符串是否包含任何字符,我建议使用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;
}
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;
}
当我正在寻找一种好的方法来检测某个字符串是价格还是句子,比如“太低以至于不显示”时。