2014-11-22 71 views
-1

如果我有一個字符串,如:字符串分割爲不同的數據類型

Bridport, Dorset, 12977, 425 

是否有使用分割功能,這樣我就可以宣佈前兩個部分字符串和後兩個部分的一種方式整數?

+1

在逗號分割會產生一個數組,然後創建變量,你可以從那裏轉換類型。 – OneFineDay 2014-11-22 20:04:10

+0

字符串的部分仍然是字符串,使用Convert或Cint [如下所示](http://stackoverflow.com/a/27080237/1070452) – Plutonix 2014-11-22 20:04:44

+0

我試過這樣做,但它表示輸入格式無效 – Todd432 2014-11-22 20:07:30

回答

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,則使用後者。

+0

使用它仍然說輸入格式無效 – Todd432 2014-11-22 20:18:11

+0

@ Todd432:我編輯了我的答案以提供安全的方法。 – 2014-11-22 20:21:32

-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 
+5

你真的應該使用[Option Strict On](http://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx)。 – 2014-11-22 20:28:39