Reputation: 301
So lets say i have a string : "a = b + c - d"
I want to create a character array that will hold these expression signs(=,-,+,) and convert them to an array for example in this case the array would be {'=','+','-'}
example of the code:
string s = "a = b + c -d"
char[] array = s.???('=','-','+');
is there an easy way to this is without loops?
Thanks in advance :)
Upvotes: 2
Views: 59
Reputation: 236328
You can use LINQ to select characters which are not letters or whitespace
var array = s.Where(c => !Char.IsLetter(c) && !Char.IsWhiteSpace(c)).ToArray();
Output:
[ '=', '+', '-' ]
You can also create extension method to make code more readable and select only math operators
public static class Extensions
{
private static HashSet<char> mathOperators =
new HashSet<char>(new[] { '+', '-', '=' }); // add more symbols here
public static bool IsMathOperator(this char c) => mathOperators.Contains(c);
}
And usage
var array = s.Where(c => c.IsMathOperator()).ToArray();
Upvotes: 2
Reputation: 7713
You could use linq and do something like this:
char[] operators = new char[] { '=', '-', '+' };
string s = "a = b + c -d";
var opArray = s.Where(x=>operators.Contains(x)).ToArray();
You can add all the operators you need in the operators
array
Upvotes: 4