如何洗掉所有字串而不是什么都不寫?因為沒有任何東西實際上意味著一條沒有任何東西的線,但是這條線存在。我希望它不再存在!
Dim textfile() As String = IO.File.ReadAllLines(My.Application.Info.DirectoryPath ("\textfile.txt"))
For i As Integer = 0 To textfile.Count - 1
If textfile(i).Length > 1 Then
textfile(i) = Nothing 'here i want to delete
End if
Next
uj5u.com熱心網友回復:
您可以使用 LINQ 僅選擇非空行:
Dim textfile = IO.File.ReadAllLines(IO.Path.Combine(My.Application.Info.DirectoryPath, "textfile.txt"))
Dim filteredTextFile = textfile.Where(Function(line) Not String.IsNullOrWhitespace(line)).ToArray()
小提琴:https : //dotnetfiddle.net/nUpjEH
uj5u.com熱心網友回復:
您需要過濾掉空行,然后寫入檔案。接受的答案是第一部分,所以這是完整的解決方案
Dim textFile = File.ReadAllLines("filename.txt")
Dim fixedLines = textFile.Where(Function(line) Not String.IsNullOrWhiteSpace(line))
File.WriteAllLines("filename.txt", fixedLines)
@HansPassant 在評論中指出這不是最有效的解決方案。這是使用 StreamReader / StreamWriter 的另一種方法
Dim lines As New List(Of String)()
Using sr As New StreamReader("filename.txt")
While Not sr.EndOfStream
Dim line = sr.ReadLine()
If Not String.IsNullOrWhiteSpace(line) Then lines.Add(line)
End While
End Using
Using sw As New StreamWriter("filename.txt")
For Each line In lines
sw.WriteLine(line)
Next
End Using
但是,使用帶有幾行空行的 1kb 檔案 ~1000 行檔案,我的系統第一種方法大約需要 18 毫秒,第二種方法需要 18 毫秒(每個平均 1000 次)。所以至少在我的系統中,在這種情況下,沒有太大的區別。如果效率是一個問題,請參閱https://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/進行進一步分析。
uj5u.com熱心網友回復:
據此,If textfile(i).Length > 1 Then您似乎只希望保留短線。而你nothing只設定長的
使用 LINQ 執行此操作
Dim onlyShortLines() as String =
textfile.Where(Func(x) x.Length = 1).Select(Func(x) x).ToArray()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405789.html
標籤:
