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.
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.
Although a simple example like that is probably good enough using ||
, you can also use Regex for it:
if (Regex.IsMatch(mystring, @"[-+*/]$")) {
...
}
If you really want to, you can use De Morgan's laws to replace x || y
in your code. One version says:
!(x || y) == !x && !y
If you want to have the same result, we just need to negate the entire expression twice:
x || y == !!(x || y) == !(!x && !y)
If you are using .NET 3.5 then it is quite easy with LINQ:
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
Test the last char of the string using String.IndexOfAny(Char[], Int32)
method (assuming str
is your variable):
str.IndexOfAny(new char[] {'+', '-', '*', '/'}, str.Length - 1)
Complete expression:
str.Lenght > 0 ? str.IndexOfAny(new char[] {'+', '-', '*', '/'}, str.Length - 1) != -1 : false
Given the complete lack of context, would this solution that is worse than using an easy ||
operator be of use:
Boolean check = false;
if (myString.EndsWith("+"))
check = true;
if (!check && myString.EndsWith("-"))
check = true;
if (!check && myString.EndsWith("/"))
check = true;
etc.
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;
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.
Using String.IndexOf(String)
:
str.Lenght > 0 ? "+-*/".IndexOf(str[str.Lenght - 1]) != -1 : false