问题描述
有没有一种方法来分析运营商在字符串等式中使用?
Is there a way to parse operators in String to use in an equation?
例:5 + 4
在这种情况下,5个和4都是字符串,但我可以通过使用for循环把它解析为整数,对不对?但怎么样+操作?
In this case, the 5 and 4 are strings, but I can parse them to integer by using a for loop, right? But what about the + operator?
好吧,我用ChrisF的解决方案
Okay I used ChrisF's solution
推荐答案
海报似乎已经解决了他的问题,但以防万一有人发现这个职位找我做了一个非常简单的解决答案。
The poster seems to have solved his problem, but just in case someone finds this post looking for an answer I have made a very simple solution.
Dim s As String = "5 * 4" 'our equation
s = s.Replace(" ", "") 'remove spaces
Dim iTemp As Double = 0 'double (in case decimal) for our calculations
For i As Integer = 0 To s.Length - 1 'standard loop
If IsNumeric(s(i)) Then
iTemp = Convert.ToInt32(s(i)) - 48 'offset by 48 since it gets ascii value when converted
Else
Select Case s(i)
Case "+"
'note s(i+1) looks 1 index ahead
iTemp = iTemp + (Convert.ToInt32(s(i + 1)) - 48)'solution
Case "-"
iTemp = iTemp - (Convert.ToInt32(s(i + 1)) - 48)'solution
Case "*"
iTemp = iTemp * (Convert.ToInt32(s(i + 1)) - 48)'solution
Case "/"
'you should check for zero since x/0 = undefined
iTemp = iTemp / (Convert.ToInt32(s(i + 1)) - 48)'solution
End Select
Exit For 'exit since we are done
End If
Next
MsgBox(iTemp.ToString)
这仅仅是一个简单快速和肮脏的解决方案。我在学校(许多很久以前)学到的方法是做这些类型的堆栈与问题。复杂的数学字符串可以使用堆栈进行解析。
This is just a simple quick and dirty solution. The way I learned in school (many many moons ago) was to do these types of problems with stacks. Complex mathematical strings can be parsed using stacks.
这篇关于解析字符串用VB等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!