如何使用string.Endswith来测试多个结局?
我需要从以下任何运算符中检入string.Endswith("")
: +,-,*,/
如果我有20个运营商,我不想使用||
操作员19次。
如果您使用的是.NET 3.5,那么LINQ非常简单:
string test = "foo+"; string[] operators = { "+", "-", "*", "/" }; bool result = operators.Any(x => test.EndsWith(x));
虽然使用||
这样的简单例子可能已经足够了 ,你也可以使用正则表达式:
if (Regex.IsMatch(mystring, @"[-+*/]$")) { ... }
string s = "Hello World +"; string endChars = "+-*/";
使用function:
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
使用LINQ:
bool endsWithAny = endChars.Contains(s.Last());
使用TrimEnd:
bool endsWithAny = s.TrimEnd(endChars.ToCharArray()).Length < s.Length; // als possible s.TrimEnd(endChars.ToCharArray()) != s;
怎么样:-
string input = .....; string[] matches = { ...... whatever ...... }; foreach (string match in matches) { if (input.EndsWith(match)) return true; }
我知道在这种情况下避免LINQ是一个可怕的老派,但有一天你需要阅读这段代码。 我绝对相信LINQ有它的用途(也许我会在某一天找到它们)但我很确定它并不是要替换上面的四行代码。
如果你真的想,你可以使用De Morgan定律代替x || y
你的代码中的x || y
。 一个版本说:
!(x || y) == !x && !y
如果你想得到相同的结果,我们只需要将整个表达式否定两次:
x || y == !!(x || y) == !(!x && !y)
使用String.IndexOfAny(Char[], Int32)
方法测试字符串的最后一个字符(假设str
是你的变量):
str.IndexOfAny(new char[] {'+', '-', '*', '/'}, str.Length - 1)
完整表达:
str.Lenght > 0 ? str.IndexOfAny(new char[] {'+', '-', '*', '/'}, str.Length - 1) != -1 : false
正则表达式是不是一种选择
鉴于完全缺乏上下文,这种解决方案是否比使用简单的||
更糟糕 操作员有用:
Boolean check = false; if (myString.EndsWith("+")) check = true; if (!check && myString.EndsWith("-")) check = true; if (!check && myString.EndsWith("/")) check = true; etc.
使用String.IndexOf(String)
:
上述就是C#学习教程:如何使用string.Endswith来测试多个结局?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
str.Lenght > 0 ? "+-*/".IndexOf(str[str.Lenght - 1]) != -1 : false
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1015805.html