답변:
단일 문자를 찾는 경우 String.IndexOfAny().
임의의 문자열을 원하는 경우 정규식이 작동하지만 "직접"을 달성하는 .NET 메서드를 알지 못합니다.
음, 항상 이것이 있습니다.
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (string needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
용법:
bool anyLuck = s.ContainsAny("a", "b", "c");
||그러나 비교 체인의 성능과 일치하는 것은 없습니다 .
public static bool ContainsAny(this string haystack, params string[] needles) { return needles.Any(haystack.Contains); }
다음은 거의 동일하지만 더 확장 가능한 LINQ 솔루션입니다.
new[] { "a", "b", "c" }.Any(c => s.Contains(c))
var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);
정규식으로 시도 할 수 있습니다.
string s;
Regex r = new Regex ("a|b|c");
bool containsAny = r.IsMatch (s);
특정 StringComparison(예 : 대소 문자 무시) 이 포함 된 ContainsAny가 필요한 경우이 문자열 확장 메서드를 사용할 수 있습니다.
public static class StringExtensions
{
public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
{
return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
}
}
사용 StringComparison.CurrentCultureIgnoreCase:
var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.
”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.
문자열은 문자 모음이므로 LINQ 확장 메서드를 사용할 수 있습니다.
if (s.Any(c => c == 'a' || c == 'b' || c == 'c')) ...
이것은 문자열을 한 번 스캔하고 일치가 발견 될 때까지 각 문자에 대해 문자열을 한 번 스캔하는 대신 첫 번째 발생에서 중지합니다.
예를 들어 문자 범위를 확인하는 등 원하는 표현식에 사용할 수도 있습니다.
if (s.Any(c => c >= 'a' && c <= 'c')) ...
// Nice method's name, @Dan Tao
public static bool ContainsAny(this string value, params string[] params)
{
return params.Any(p => value.Compare(p) > 0);
// or
return params.Any(p => value.Contains(p));
}
Any모두를 All위해
static void Main(string[] args)
{
string illegalCharacters = "!@#$%^&*()\\/{}|<>,.~`?"; //We'll call these the bad guys
string goodUserName = "John Wesson"; //This is a good guy. We know it. We can see it!
//But what if we want the program to make sure?
string badUserName = "*_Wesson*_John!?"; //We can see this has one of the bad guys. Underscores not restricted.
Console.WriteLine("goodUserName " + goodUserName +
(!HasWantedCharacters(goodUserName, illegalCharacters) ?
" contains no illegal characters and is valid" : //This line is the expected result
" contains one or more illegal characters and is invalid"));
string captured = "";
Console.WriteLine("badUserName " + badUserName +
(!HasWantedCharacters(badUserName, illegalCharacters, out captured) ?
" contains no illegal characters and is valid" :
//We can expect this line to print and show us the bad ones
" is invalid and contains the following illegal characters: " + captured));
}
//Takes a string to check for the presence of one or more of the wanted characters within a string
//As soon as one of the wanted characters is encountered, return true
//This is useful if a character is required, but NOT if a specific frequency is needed
//ie. you wouldn't use this to validate an email address
//but could use it to make sure a username is only alphanumeric
static bool HasWantedCharacters(string source, string wantedCharacters)
{
foreach(char s in source) //One by one, loop through the characters in source
{
foreach(char c in wantedCharacters) //One by one, loop through the wanted characters
{
if (c == s) //Is the current illegalChar here in the string?
return true;
}
}
return false;
}
//Overloaded version of HasWantedCharacters
//Checks to see if any one of the wantedCharacters is contained within the source string
//string source ~ String to test
//string wantedCharacters ~ string of characters to check for
static bool HasWantedCharacters(string source, string wantedCharacters, out string capturedCharacters)
{
capturedCharacters = ""; //Haven't found any wanted characters yet
foreach(char s in source)
{
foreach(char c in wantedCharacters) //Is the current illegalChar here in the string?
{
if(c == s)
{
if(!capturedCharacters.Contains(c.ToString()))
capturedCharacters += c.ToString(); //Send these characters to whoever's asking
}
}
}
if (capturedCharacters.Length > 0)
return true;
else
return false;
}
정규식 을 사용할 수 있습니다.
if(System.Text.RegularExpressions.IsMatch("a|b|c"))
trie데이터 구조를 찾아보십시오 .