What's the easiest way to search for a string within a memory stream (and multiple strings) and return true or false?
            Asked
            
        
        
            Active
            
        
            Viewed 5,202 times
        
    1
            
            
        - 
                    3Use e.g. [`Pos`](http://docwiki.embarcadero.com/Libraries/XE2/en/System.Pos) function and this [`piece of code`](http://stackoverflow.com/a/733322/960757). – TLama Apr 11 '13 at 14:00
- 
                    1start with fixing them to have the same encoding or charset. The same string value provides for ansolutely different byte values (TMemoryStream) in UTF-8, UTF-16 and non-Unicode encodings. – Arioch 'The Apr 11 '13 at 14:04
- 
                    http://en.wikipedia.org/wiki/String_search – Arioch 'The Apr 11 '13 at 14:05
- 
                    Do you ask about searching for one string in "multiple strings" or do you ask about searching for "multiple strings" within one memory stream ? – Arioch 'The Apr 11 '13 at 14:10
1 Answers
2
            
            
        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)
 
    
    
        Vector
        
- 10,879
- 12
- 61
- 101
- 
                    1In the newer Delphi versions TStringStream.Create has an overload that accepts TEncoding: http://docwiki.embarcadero.com/Libraries/XE2/en/System.Classes.TStringStream.Create – iPath ツ Apr 16 '13 at 14:39
