2010-12-16 188 views
0

我想兩個字符串在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 

誰能一個糾正的邏輯,如果有任何錯誤在比較?

+1

你是什麼意思?按字母順序?或者你想做一個數字比較? – 2010-12-16 12:07:06

+0

如果您開始接受以前問題的有用答案,您可能會得到更多/更好的答覆。 – 2010-12-16 12:09:49

回答

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) 
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) { ... }

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 

我推薦總是使用整數來表示數值,特別是如果你想比較它們。比較數字值後,可以將值格式化爲字符串。