![](/img/trans.png)
[英]VB.NET Delete specific number of last characters in string in excel
[英]Delete specific array string in VB.Net
如何刪除所有字符串而不是什么都不寫? 因為沒有任何東西實際上意味着一條沒有任何東西的線,但是這條線存在。 我希望它不再存在!
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
您只能使用 LINQ 到 select 不為空的行:
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()
您需要過濾掉空行,然后寫入文件。 接受的答案是第一部分,所以這是完整的解決方案
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/進一步分析。
根據這個If textfile(i).Length > 1 Then
你似乎只希望保留短行。 而你nothing
為長的
使用 LINQ 執行此操作
Dim onlyShortLines() as String =
textfile.Where(Func(x) x.Length = 1).Select(Func(x) x).ToArray()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.