2

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

1
  • Do you have a list of operators you're looking for? Does the order in the resulting array matter? Commented Mar 10, 2017 at 13:03

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

This is a nice solution, but i may also add !Char.IsDigit(c), just in case
@Pikoh maybe list of valid operators is better in that case. That depends whether OP formulas use digits and whether there is lot of valid operators :)
that why i suggested my answer, but i agree, it depends on OP formulas :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.