gpt4 book ai didi

vb.net - 如何获取包含字符串的整行文本

转载 作者:行者123 更新时间:2023-12-02 02:25:15 38 4
gpt4 key购买 nike

有一件事我想问一下。如何在 Visual Basic 2010 中获取包含字符串的整行文本?

比方说:

MyText.txt 文件包含:

Configurations: 
Name: Fariz Luqman
Age: 78
My Favourite Fruit: Lemon, Apple, Banana
My IPv4 Address: 10.6.0.5
My Car: Ferrari

在 Visual Basic 中,我想要获取包含字符串“Banana”的整行文本并将其打印在文本框中,以便它将显示在该文本框中:

My Favourite Fruit: Lemon, Apple, Banana

我为什么要这么做?因为文本文件是被附加的并且行号是随机的。内容也是随机的,因为文本是由 Visual Basic 生成的。文本“Banana”可以位于第 1 行、第 2 行,也可以位于任何行,那么如何获取包含特定字符串的整行文本?

提前谢谢您!

最佳答案

您可以使用 LINQ 在一行中轻松完成此操作:

TextBox1.Text = File.ReadAllLines("MyText.txt").FirstOrDefault(Function(x) x.Contains("Banana"))

但是,如果文件相当大,则效率不是特别高,因为它会在搜索行之前将整个文件读入内存。如果您想让它在找到该行后停止加载文件,可以使用 StreamReader,如下所示:

Using reader As New StreamReader("Test.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains("Banana") Then
TextBox1.Text = line
Exit While
End If
End While
End Using

关于vb.net - 如何获取包含字符串的整行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030827/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com