Reputation: 6040
I needed to test a string to see whether it ends with any of an array of strings.
I found the perfect solution using LINQ by following this answer:
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
Now I want to get the string that matched and that's where I'm currently stuck with.
I tried adding at the end
text_field.Text = x;
and that errored out with a message about scope - and rightfully so, I was expecting that error. I also tried to declare a string variable named x
at the very top and another error came out of it - something about not being able to re-declare the variable in a different scope. I guess I'm used to PHP so much where you can re-declare a variable with no issues.
Upvotes: 1
Views: 682
Reputation: 3261
If i understand right, this will get you the operator
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
var result = operators.Where(x => test.EndsWith(x)) ;
This will only return the last used operator so if it ends in -+* it will give you the last character in the string
Upvotes: 0
Reputation: 2918
Your best bet is to do a FirstOrDefault
and then check if that is null/empty/etc as if it were your bool. Though this is a very basic example it should get the point across. What you do with that result and if it should just be one or more, etc is up to your circumstances.
static void Main()
{
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
string actualResult = operators.FirstOrDefault(x => test.EndsWith(x));
if (result)
{
Console.WriteLine("Yay!");
}
if (!string.IsNullOrWhiteSpace(actualResult))
{
Console.WriteLine("Also Yay!");
}
}
Upvotes: 1
Reputation: 12546
I would use Regex for this
string test = "foo+";
var match = Regex.Match(test, @".+([\+\-\*\\])$").Groups[1].Value;
match will be ""
if the string doesn't end with +-*/
Upvotes: 2