Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string.Endswith to test for multiple endings?

Tags:

string

c#

I need to check in string.Endswith("") from any of the following operators: +,-,*,/

If I have 20 operators I don't want to use || operator 19 times.

like image 608
neven Avatar asked Sep 02 '25 01:09

neven


2 Answers

If you are using .NET 3.5 (and above) then it is quite easy with LINQ:

string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
like image 61
Mark Byers Avatar answered Sep 06 '25 23:09

Mark Byers


Although a simple example like that is probably good enough using ||, you can also use Regex for it:

if (Regex.IsMatch(mystring, @"[-+*/]$")) {
  ...
}
like image 28
Max Shawabkeh Avatar answered Sep 06 '25 23:09

Max Shawabkeh