文字列の比較には、幾つかの方法があります。その方法を記載します。
文字列を比較する
Dim str1 As String = "12345"
Dim str2 As String = "67890"
If str1 < str2 Then
MessageBox.Show(str2 & " の方が大きい")
End If
又は
If str1.CompareTo(str2) < 0 Then
MessageBox.Show(str2 & " の方が大きい")
End If
又は
If String.Compare(str1, str2) < 0 Then
MessageBox.Show(str2 & " の方が大きい")
End If
分かりにくいのでCase文にすると以下のようになります
Select Case str1.CompareTo(str2)
Case 0
MessageBox.Show("等しい")
Case Is > 0
MessageBox.Show(str1 & " の方が大きい")
Case Is < 0
MessageBox.Show(str2 & " の方が大きい")
End Select
文字列を大文字小文字を区別しないで比較する
Dim str1 As String = "ABCDEF"
Dim str2 As String = "abcdef"
If String.Compare(str1, str2, True) = 0 Then
MessageBox.Show("等しい")
End If
先頭文字列または末尾文字列と一致するか比較する
Dim str As String = "ABCDEabcdeあいう"
'先頭の文字列と一致するかどうかを判断する
If str.StartsWith("ABCDE") Then
MessageBox.Show("先頭の文字列と一致")
End If
'末尾の文字列と一致するかどうかを判断する
If str.EndsWith("あいう") Then
MessageBox.Show("末尾の文字列と一致")
End If
空の文字列を比較する
Dim str As String = String.Empty
又は
Dim str As String = ""
If str = String.Empty Then
MessageBox.Show("空の文字列")
End If
If str.Length = 0 Then
MessageBox.Show("空の文字列")
End If
If str = "" Then
MessageBox.Show("空の文字列")
End If
If str.CompareTo("") = 0 Then
MessageBox.Show("空の文字列")
End If
If String.Compare(str, "") = 0 Then
MessageBox.Show("空の文字列")
End If
以上の結果は全て空の文字列となる
String.Equals メソッドを使用する方法
Equals は、StringComparison列挙体の値を指定することができ、大文字と小文字を区別しない比較や、カルチャに依存した比較ができます。
Dim str1 As String = "ABCDEF" Dim str2 As String = "abcdef" Dim bc1 As Boolean = str1.Equals(str2, StringComparison.CurrentCulture) Dim bc2 As Boolean = str1.Equals(str2, StringComparison.CurrentCultureIgnoreCase)