问题
I've read a file into StringBuilder. When I give a string as an input, if the word is present in the file, the output should be true.. If its not present, it should be false.. How do i do it? Could someone help me with the code? I've written the program till here.. How do i go further? Thanks alot.. :)
class Program
{
static void Main(string[] args)
{
using (StreamReader Reader = new StreamReader("C://myfile2.txt"))
{
StringBuilder Sb = new StringBuilder();
Sb.Append(Reader.ReadToEnd());
{
Console.WriteLine("The File is read");
}
}
}
}
回答1:
using (System.IO.StreamReader Reader = new System.IO.StreamReader("C://myfile2.txt"))
{
string fileContent = Reader.ReadToEnd();
if (fileContent.Contains("your search text"))
return true;
else
return false;
}
回答2:
How about an one-liner:
bool textExists = System.IO.File.ReadAllText("C:\\myfile2.txt").Contains("Search text");
That should do the trick :)
回答3:
In the example you show - there is no point loading into a StringBuilder
in the first place. You already return the entire string in the call to StreamReader.ReadToEnd
, so you may as well just check if this contains your substring.
StringBuilder is very useful if you are changing and mutating the string - but in this use case, you are not.
How about this:
private bool FileContainsString(string file, string substring)
{
using (StreamReader reader = new StreamReader("C://myfile2.txt"))
{
return reader.ReadToEnd().Contains(substring);
}
}
If you definitely want the string builder, then something like this:
private bool FileContainsString(string file, string substring)
{
using (StreamReader reader = new StreamReader("C://myfile2.txt"))
{
var sb = new StringBuilder(reader.ReadToEnd());
return sb.ToString().Contains(substring);
}
}
but in this specific scenario the StringBuilder is not actually doing anything useful.
回答4:
You can read the whole file into a string with File.ReadAllText
. Note that this does load the whole file at once, and thus costs a lot of memory if the file is large:
string content = File.ReadAllText(@"C:\myfile2.txt");
Console.WriteLine(content.Contains("needle"));
If your needle
doesn't span multiple lines you can go with:
IEnumerable<string> content = File.ReadLines(@"C:\myfile2.txt");
Console.WriteLine(content.Any(line => line.Contains("needle")));
This only needs to keep one line in memory at a time, and thus scaled to larger files.
回答5:
Assign that to a string and then check if it contains the substring.
dim str as string
str = sb.tostring()
if str.contains("string") then
'code
else
'code
end if
来源:https://stackoverflow.com/questions/9785650/using-a-string-builder-ive-read-a-file-how-do-i-find-if-the-given-string-is