问题
What's the easiest way to search for a string within a memory stream (and multiple strings) and return true or false?
回答1:
var ms:TMemoryStream;
strS:TStringStream;
aStr:string;
aPos:integer;
found:boolean;
begin
ms:=TMemoryStream.Create;
ms.LoadFromFile('c:\aFile.txt');
strS:=TStringStream.Create;
strS.LoadFromStream(ms);
aPos:=pos(aStr,strS.dataString);
found:=aPos>0;
end;
TStringStream is an often forgetten but very useful tool - easier and safer than messing with pChars, etc.
For multiple searches, either ackwardly loop using pos,substring, etc or use a RegEx.
This code works fine in Delphi XE, although TStringStream is very old - not sure if it is unicode compliant.
(The example is leaky - I left out the finalization code for the sake of brevity)
来源:https://stackoverflow.com/questions/15950649/delphi-easiest-way-to-search-for-string-in-memorystream