如何使用string.Endswith来测试多个结局?

nev*_*ven 19 c# string

我需要string.Endswith("")从以下任何运营商办理登机手续:+,-,*,/

如果我有20个运算符,我不想使用||运算符19次.

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)

  • 我发现在初始化类似的东西时只使用数组更清楚:var operators = new [] {"+", "-", "*", "/"};`。或者只是: bool result = new [] {"+", "-", "*", "/"}.Any(x => test.EndsWith(x));` (2认同)
  • 稍微短一点的版本是“bool result =operators.Any(test.EndsWith);” (2认同)

Max*_*keh 9

虽然这样的简单示例可能已经足够好用||,但您也可以使用Regex:

if (Regex.IsMatch(mystring, @"[-+*/]$")) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 我个人不愿意推荐RegEx.对于所提出的问题,这只是最慢的解决方案,也是最复杂的解决方案. (4认同)
  • 你知道,每次出现字符串问题时,大多数人都会跳上正则表达式,但这种情况我认为正则表达式实际上是*干净,简洁,易于理解,易于维护.......如果你知道正则表达式. (3认同)
  • "如果你知道正则表达",就说明了一切.我与正则表达式的问题是双重的.我从来没有正确地学习它们.如果必须的话,我可以使用它们,但是我不会花大部分时间来修改字符串,所以我从来没有学过它们.这意味着当我正在查看或阅读或调试代码时,我必须停止并多次读取包含正则表达式的行.必须多次读取的行是隐藏错误的好方法.此外,如果要解析的下一个运算符是"||",则此解决方案非常复杂.编译和解析正则表达式当然不是免费的. (2认同)

Kob*_*obi 5

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)