如何搜索特定字符串并返回整行?在VB.NET中 [英] How can I search for a specific string and return whole line? In VB.NET
本文介绍了如何搜索特定字符串并返回整行?在VB.NET中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从My.Resources.filetxt搜索特定字符串并返回整行?
how can I search for a specific string from My.Resources.filetxt and return whole line?
e.g My.Resources.filetxt has following entries say :
england is cold country
england is cold country
england is cold country
现在我想在这个txt文件中搜索字符串england并返回整行包含这个字符串。我该怎么办
我的尝试:
now i want to search this txt file for a string "england" and return the entire line containing this string. How can i do it
What I have tried:
Findstring = My.Resources.filetxt
Lookfor = TextBox2.Text
'TextBox1.Text = IO.File.ReadAllLines(My.Resources.filetxt).FirstOrDefault(Function(x) x.Contains(Lookfor))
推荐答案
两种方法:
1)将文本拆分为单独的行,并在每行中搜索文本。这不是特别有效,特别是如果您的文本很长并且包含许多行,因为它会生成许多单独的字符串。它很容易实现 - 几行代码。
2)使用IndexOf依次查找字符串的每个出现:String.IndexOf Method(String,Int32)(System) [ ^ ]。然后,您可以使用返回的索引再次使用它来查找行的末尾,并且 String.LastIndexOf方法(String,Int32)(系统) [ ^ ]找到开头。然后,您可以使用 String.Substring方法(Int32,Int32)提取整行。 (系统) [ ^ ]。这是一个更多的工作,但会更快,并且整个负载更少的内存猪!
Two ways to do it:
1) Split the text into separate lines, and search each line for your text. This isn't particularly efficient, particularly if your text is long and contains many lines as it generates a lot of separate strings. It is easy to implement though - a couple of lines of code.
2) Use IndexOf to find each occurance of the string in turn: String.IndexOf Method (String, Int32) (System)[^]. You can then use it again with the returned index to find the end of the line, and String.LastIndexOf Method (String, Int32) (System)[^] to find the beginning. You can then extract the whole line using String.Substring Method (Int32, Int32) (System)[^]. This is a little more work, but will be a lot quicker, and a whole load less of a memory hog!
这篇关于如何搜索特定字符串并返回整行?在VB.NET中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文