【问题标题】:I have two arrays and a text file and i want it to put a specific word into one array and someting else into the other (VB)我有两个数组和一个文本文件,我希望它将一个特定的单词放入一个数组中,并将其他一些单词放入另一个数组中(VB)
【发布时间】:2013-10-25 07:39:59
【问题描述】:
所以我在 Visual Basic 中有一个问题,我有两个数组,分别称为 arrLang1 和 arrLang2
我想将 - 之前的单词放入第一个数组,将 - 之后的单词放入第二个数组。而这些文字来自一个txt文件。
SwedishWord1 - EnglishWord1
SwedishWord2 - EnglishWord2
SwedishWord3 - EnglishWord3
SwedishWord4 - EnglishWord4
【问题讨论】:
标签:
arrays
vb.net
streamreader
【解决方案1】:
为什么不改用Dictionary(Of String. String)?它们是专门为这种要求而创建的。
Dictionary<TKey, TValue> 泛型类提供从一组键到一组值的映射。字典中的每个添加都包含一个值及其关联的键。使用其键检索值非常快,接近 O(1)。每个键都必须唯一。
Dim allLines = From line In File.ReadLines(path) Where Not String.IsNullOrWhiteSpace(line)
Dim dict = New Dictionary(Of String, String)
For Each line As String In allLines
Dim words = line.Split({" - "}, StringSplitOptions.RemoveEmptyEntries)
If words.Length >= 2 Then
dict(words(0)) = words(1)
End If
Next
如果您坚持收集我会使用 List(Of String) 而不是数组,因为您不知道正确的大小并且数组是固定大小的:
Dim swedishWords = New List(Of String)
Dim englishWords = New List(Of String)
For Each line As String In allLines
Dim words = line.Split({" - "}, StringSplitOptions.RemoveEmptyEntries)
If words.Length >= 2 Then
swedishWords.Add(words(0))
englishWords.Add(words(1))
End If
Next
如果你之后真的需要数组swedishWords.ToArray() 和englishWords.ToArray()。