将字符串拆分为不同的数据类型

时间:2014-11-22 20:01:52

标签: vb.net

如果我有一个字符串,如:

Bridport, Dorset, 12977, 425

有没有办法使用split函数,所以我可以将前两个部分声明为字符串,将后两部分声明为整数?

2 个答案:

答案 0 :(得分:2)

您可以将其拆分为String(),然后使用Int32.Parse将最后两个解析为整数。

Dim tokens = text.Split(","c)
Dim part1 As String = tokens(0).Trim()
Dim part2 As String = tokens(1).Trim()
Dim part3 As Int32  = Int32.Parse(tokens(2).Trim())
Dim part4 As Int32  = Int32.Parse(tokens(3).Trim())

如果您不知道格式是否有效,可以使用此超级安全版本:

Dim part1 As String = tokens(0).Trim()
Dim part2 As String = tokens.ElementAtOrDefault(1)
If part2 IsNot Nothing Then part2 = part2.Trim()
Dim part3 As String = tokens.ElementAtOrDefault(2)
Dim part4 As String = tokens.ElementAtOrDefault(3)
Dim num1 As Int32? = New Nullable(Of Int32)
Dim num2 As Int32? = New Nullable(Of Int32)
If part3 IsNot Nothing Then
    Dim num As Int32
    If Int32.TryParse(part3.Trim(), num) Then
        num1 = num
    End If
End If
If part4 IsNot Nothing Then
    Dim num As Int32
    If Int32.TryParse(part4.Trim(), num) Then
        num2 = num
    End If
End If

我使用Nullable(Of Integer)来了解该字符串是否可以成功解析为Integer。它具有HasValueValue属性。如果HasValue返回True,请使用后者。

答案 1 :(得分:-1)

Dim info as string = "Bridport,Dorset,12977,425"
Dim split as string() = info.split(",")
Dim string1 as string = split(0) ' Reads Bridport
Dim string2 as string = split(1) ' Reads Dorset
Dim int1 as integer = split(2) ' Reads 12977
Dim int2 as integer = split(3) ' Reads 425