Mar*_*ers 40
如果您使用的是.NET 3.5,那么使用LINQ非常容易:
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
Run Code Online (Sandbox Code Playgroud)
虽然这样的简单示例可能已经足够好用||
,但您也可以使用Regex:
if (Regex.IsMatch(mystring, @"[-+*/]$")) {
...
}
Run Code Online (Sandbox Code Playgroud)
string s = "Hello World +";
string endChars = "+-*/";
Run Code Online (Sandbox Code Playgroud)
使用函数:
private bool EndsWithAny(string s, params char[] chars)
{
foreach (char c in chars)
{
if (s.EndsWith(c.ToString()))
return true;
}
return false;
}
bool endsWithAny = EndsWithAny(s, endChars.ToCharArray()); //use an array
bool endsWithAny = EndsWithAny(s, '*', '/', '+', '-'); //or this syntax
Run Code Online (Sandbox Code Playgroud)
使用 LINQ:
bool endsWithAny = endChars.Contains(s.Last());
Run Code Online (Sandbox Code Playgroud)
使用修剪结束:
bool endsWithAny = s.TrimEnd(endChars.ToCharArray()).Length < s.Length;
// als possible s.TrimEnd(endChars.ToCharArray()) != s;
Run Code Online (Sandbox Code Playgroud)