比较字符串
问题描述:
我想两个字符串在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
谁能一个纠正的逻辑,如果有任何错误在比较?
答
你是什么意思按长度或内容比较?
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)
答
您正在比较字符串,而不是整数。
您可以将它们作为整数进行比较,将“$”替换为“”,然后将其转换为整数。
替换$为 “”
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) { ... }
答
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
我推荐总是使用整数来表示数值,特别是如果你想比较它们。比较数字值后,可以将值格式化为字符串。
你是什么意思?按字母顺序?或者你想做一个数字比较? – 2010-12-16 12:07:06
如果您开始接受以前问题的有用答案,您可能会得到更多/更好的答复。 – 2010-12-16 12:09:49