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

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

if (Regex.IsMatch(mystring, @"[-+*/]$")) {
  ...
}

How about:-

string input = .....;
string[] matches = { ...... whatever ...... };

foreach (string match in matches)
{
    if (input.EndsWith(match))
        return true;
}

I know it is dreadfully old school to avoid LINQ in this context, but one day you will need to read this code. I am absolutely sure that LINQ has its uses (maybe i'll find them one day) but i am quite sure it is not meant to replace the four lines of code above.


string s = "Hello World +";
string endChars = "+-*/";

Using a 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

Using LINQ:

bool endsWithAny = endChars.Contains(s.Last());

Using TrimEnd:

bool endsWithAny = s.TrimEnd(endChars.ToCharArray()).Length < s.Length;
// als possible s.TrimEnd(endChars.ToCharArray()) != s;

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));

Tags:

C#

String