开发者

Comparing Strings

开发者 https://www.devze.com 2023-01-30 17:29 出处:网络
I would like to compare two strings in a vb.net windows application Imports System.Windo开发者_如何学Pythonws

I would like to compare two strings in a vb.net windows application

Imports System.Windo开发者_如何学Pythonws

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

Could anyone one correct the logic if there is any mistake in that?


You are comparing strings, not integers.

You could compare them as integers by replacing "$" with "" and then convert it to an integer.

Replace the $ to ""

s = s.Replace("$", "");
y = y.Replace("$", "");

Convert both of them to integers

Dim result1 As Integer
Dim result2 As Integer

result1 = Convert.ToInt32(s)
result2 = Convert.Toint32(y);

Then you can do

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

I recommend always to use Integers for numeric values, particularly if you want to compare them. You can format the values as string after you compared the numeric values.


What do you mean compare by length or content?

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号