我想在vb.net windows应用程序中比较两个字符串
Imports System.Windows
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim s As String = "$99"
Dim y As String = "$9899"
If s > y Then
MessageBox.Show("Hi")
End If
End Sub
End Class
如果有任何错误,有人可以纠正逻辑吗?
答案 0 :(得分:0)
你的意思是按长度或内容进行比较?
dim result as string
dim s as string = "aaa"
dim y as string = "bbb"
if s.length = y.length then result = "SAME" '= true
if s = y then result = "SAME" '= false
MessageBox.Show(result)
答案 1 :(得分:0)
您正在比较字符串,而不是整数。
您可以将“$”替换为“”来将它们作为整数进行比较,然后将其转换为整数。
将$替换为“”
s = s.Replace("$", "");
y = y.Replace("$", "");
将它们转换为整数
Dim result1 As Integer
Dim result2 As Integer
result1 = Convert.ToInt32(s)
result2 = Convert.Toint32(y);
然后你可以做
if (result1 > result2) { ... }
答案 2 :(得分:0)
Dim sum1 As Int32 = 99
Dim sum2 As Int32 = 9899
'this works as expected because you are comparing the two numeric values'
If sum1 > sum1 Then
MessageBox.Show("$" & sum1 & " is greater than $" & sum2)
Else
MessageBox.Show("$" & sum2 & " is greater than $" & sum1)
End If
'if you really want to compare two strings, the result would be different than comparing the numeric values'
'you can work around this by using the same number of digits and filling the numbers with leading zeros'
Dim s As String = ("$" & sum1.ToString("D4")) '$0099'
Dim y As String = ("$" & sum2.ToString("D4")) '$9899'
If s > y Then
MessageBox.Show(s & " is greater than " & y)
Else
MessageBox.Show(y & " is greater than " & s)
End If
我建议总是使用Integers作为数值,特别是如果你想比较它们。比较数值后,可以将值格式化为字符串。