2009-11-09 116 views
0

正確的 - 首先,我進入陌生的地方 - 所以請善待!String Array事情!

我有一個腳本,看起來有點像這樣:

Private Function checkString(ByVal strIn As String) As String 
    Dim astrWords As String() = New String() {"bak", "log", "dfd"} 
    Dim strOut As String = "" 
    Dim strWord As String 
    For Each strWord In astrWords 
     If strIn.ToLower.IndexOf(strWord.ToLower, 0) >= 0 Then 
      strOut = strWord.ToLower 
      Exit For 
     End If 
    Next 
    Return strOut 
End Function 

它的功能是檢查輸入字符串,看看是否有這些「astrWords」都在那裏,然後返回值。

所以我寫了一些代碼來動態創建基本是這樣的那些話:

Dim extensionArray As String = "" 
    Dim count As Integer = 0 
    For Each item In lstExtentions.Items 
     If count = 0 Then 
      extensionArray = extensionArray & """." & item & """" 
     Else 
      extensionArray = extensionArray & ", ""." & item & """" 
     End If 
     count = count + 1 
    Next 
    My.Settings.extensionArray = extensionArray 
    My.Settings.Save() 

很明顯 - 它創建一個使用相同的數組列表項。該代碼的輸出是完全相同的,如果我硬編碼它 - 但是當我將代碼的第一位更改爲:Dim astrWords As String()= New String(){My.Settings.extensionArray} 而不是: Dim astrWords As String()= New String(){「bak」,「log」,「dfd」} 它開始尋找整個語句,而不是循環遍歷每個單獨的一個?

我認爲它與單詞字符串末尾的括號有關 - 但我迷路了!

任何幫助表示讚賞:)

回答

2

當您使用從字面陣列中設置該字符串,它就像您使用包含分隔字符串一個字符串:

Dim astrWords As String() = New String() {"""bak"", ""log"", ""dfd"""} 

你可能想要做的是把一個逗號分隔字符串,像"bak,log,dfd"的設置,那麼你可以把它分解得到它作爲一個數組:

Dim astrWords As String() = My.Settings.extensionArray.Split(","C) 
+0

你是一個真正的!太棒了! 非常感謝 - 開心編碼:) – 2009-11-09 15:26:52

0

您需要設置extensionArray了爲字符串數組而不是一個簡單的字符串。 注意

Dim something as String 

...定義了一個字符串,但

Dim somethingElse as String() 

...定義字符串的整個陣列。

我覺得你的代碼,你需要的東西,如:

Dim extensionArray As String() = new String(lstExtensions.Items) 
Dim count As Integer = 0 
For Each item In lstExtentions.Items 
    extensionArray(count) = item 
    count = count + 1 
Next 
My.Settings.extensionArray = extensionArray 
My.Settings.Save() 

然後在checkString開始,你需要像

Private Function checkString(ByVal strIn As String) As String 
    Dim astrWords As String() = My.Settings.extensionArray 
    ... 

還有可能把lstExtentions一個更簡單的方法。如果項目有一個'ToArray()'方法,但是我不確定你在那裏使用什麼類型的項目到項目中的項目...

0

你所做的是創建一個包含所有3話。您需要創建一個字符串數組。

New String() {"bak", "log", "dfd"} 

表示創建一個包含3個字符串值「bak」,「log」和「dfd」的新字符串數組。

New String() {My.Settings.extensionArray} 

表示創建一個新的字符串數組,其中只包含一個值,即extensionArray的內容。 (你已經設置爲「bak」,「log」,「dfd」「)。請注意,這是一個字符串,而不是一個字符串數組。你不能只用逗號創建1個字符串,你需要創建一個字符串數組。

如果要動態創建數組,你需要定義它是這樣的:

Dim astrWords As String() = New String(3) 

這將創建3米空的空間陣列。

然後可以做這樣的字符串分配給每個空間:

astrWords(0) = "bak" 
astrWords(1) = "log" 
astrWords(2) = "dfd" 

你可以做到這一點位在for循環中:

Dim count As Integer = 0 
For Each item In lstExtentions.Items 
    astrWords(count) = item 
    count = count + 1 
Next 

或者,你可以看看使用generic collection 。您可以使用Add()方法將多個字符串添加到它的方式

0

我想你想你的extensionArray是類型爲String()而不是String。當您嘗試初始化新數組時,初始化程序不知道解析出多個值。它只是看到你的單一字符串。