Answer the question
In order to leave comments, you need to log in
How to format a string into a function (C#)?
Hello.
There is a line with content: 14 - 15
The compiler treats it as if it were text.
I can't reach the "beginning".
At the input I have a string (plain text) 14 - 15
Question. How can I do the math calculation?
Subtraction.
What would the function return instead of 14 - 15
This 1
(14-15=1)
Thank you.
Answer the question
In order to leave comments, you need to log in
lam0x86 said everything correctly, I will write about the difficult path.
You need to split the string into parts consisting of numbers and operations.
In the simple case (when there are two numbers and one operation), this can be done by a single search , which will return the index of the operation symbol.
In the general case (when there are several operations in a line), you need to search in a loop and add the found parts to the list, and then process it with another loop. It is more correct, but more difficult, to take into account the priorities of operations (first multiplication, then addition).
If parentheses are possible in a string, then it is better to fill in the parts not in a list, but in a special class that will parse the received parts into a calculation tree. str.IndexOfAny(new []{'+', '-', '*', '/'})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question