2013-12-13 60 views
0

我一直有問題試圖找出一種方法來搜索數組,只需從包含信息的.txt文件中獲取代碼行。我希望能夠擺脫我將意外放入輸入文件的空返回空格(空數組元素)。刪除源自.txt文件輸入的空數組元素

我有一個數組,它讀取輸入文件中的所有行。我添加了一個樣本輸入,我將其添加到樣本輸入文件中。

Line1 
Line2 
Line3 

Line4 
Line5 

我有另一個數組,這將是所有的空間已被佔到後的finalArray,應該只是一個沒有空行返回的數組。我似乎無法解釋空迴歸元素。

我剛剛得到相同的輸出。我希望它讀作;

Line1 
Line2 
Line3 
Line4 
Line5 

這將使隨機化數組的第二部分更容易,如果我能找到解決方案來解決空數組元素。我已經添加了以下代碼以供參考。

Imports System.IO 

Module ListRandomizer 
    Sub populateArray(ByVal inputArray() As String, ByRef startArray() As String) 
     Dim pos As Integer = 0 

     For Each element As String in inputArray 
     If element <> "" Then 
      startArray(pos) = element 
     End If 
     pos += 1 
     Next 
    End Sub 

    Sub Main() 
     Dim myWriter As StreamWriter 
     Dim inputArray() As String 

     inputArray = File.ReadAllLines("sampleInput.txt") 
     myWriter = New StreamWriter("sampleOutput.txt") 

     Dim currLine As Integer = 1 
     Dim size As Integer = 0 

     For Each element As String in inputArray 
     Console.WriteLine("LINE {0}, " & element, currLine) 
       currLine += 1 

     If element <> "" Then 
      size += 1 
     End If 
     Next  

     Console.Writeline(size) 
     Dim startArray(size) As String 

     populateArray(inputArray, startArray) 

     For Each fern As String in startArray 
     Console.WriteLine("LINE {0}, " & fern, currLine) 
       currLine += 1 
     Next 

     myWriter.Close() 
     System.Console.ReadLine() 
    End Sub 
End Module 

回答

0

嘗試:

inputArray = File.ReadAllLines("sampleInput.txt").Where(Function(s) Not String.IsNullOrEmpty(s)).ToArray() 
0

使用ReadlAllText(),然後拆分()與StringSplitOptions.RemoveEmptyEntries:

inputArray = File.ReadAllText("sampleInput.txt").Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)