Back to Top

Daily Archives: 2016年10月1日

VB.NET 文字列が空か調べる

文字列(String)が空の文字列かを調べるに方法にて説明します。

等値演算子による比較

Dim s As String = ""

If s Is Nothing Then
    MessageBox.Show("文字列はNULLです")
End If

If s = "" Then
    MessageBox.Show("文字列は空です")
End If

If s = String.Empty Then
    MessageBox.Show("文字列はEmptyです")
End If

 

 

Equals メソッドによる比較

Dim s As String = ""

If s.Equals("") Then
    MessageBox.Show("文字列は空です")
End If

If s.Equals(String.Empty) Then
    MessageBox.Show("文字列はEmptyです")
End If

 

 

Nothing (NULL) か比較

Dim s As String = ""

If s Is Nothing Then
    MessageBox.Show("文字列はNULLです")
End If

※文字列は

Dim s As String

Dim s As String = “”

Dim s As String = Nothing

※以上3つとも値がことなりますので注意

 

 

VB.NET 文字列の先頭・末尾の指定文字を削除する

文字列の先頭または末尾にある指定文字を削除する方法を説明します。

文字の削除には、String.Trim メソッドを使用します。

Dim str As String = "A.,:; 12345 .,:;A"

'先頭と末尾の".,:;A"文字を削除する
Dim s1 As String = str.Trim("."c, ","c, ":"c, ";"c, "A"c)
'または
Dim s1 As String = str.Trim(New Char() {"."c, ","c, ":"c, ";"c, "A"c})


'先頭の".,:;A"文字を削除する
Dim s2 As String = str.TrimStart("."c, ","c, ":"c, ";"c, "A"c)
'または
Dim s2 As String = str.TrimStart(New Char() {"."c, ","c, ":"c, ";"c, "A"c})


'末尾の".,:;A"文字を削除する
Dim s3 As String = str.TrimEnd("."c, ","c, ":"c, ";"c, "A"c)
'または
Dim s3 As String = str.TrimEnd(New Char() {"."c, ","c, ":"c, ";"c, "A"c})

※あと正規表現にて削除する方法もあります。