2013-04-11 41 views
1

在內存流(和多個字符串)中搜索字符串並返回true或false的最簡單方法是什麼?Delphi:在內存流中搜索字符串的最簡單方法

+3

使用例如['Pos'](http://docwiki.embarcadero.com/Libraries/XE2/en/System.Pos)函數和這個['piece of code'](http://stackoverflow.com/a/733322/960757 )。 – TLama 2013-04-11 14:00:04

+1

首先解決它們具有相同的編碼或字符集。相同的字符串值以UTF-8,UTF-16和非Unicode編碼提供了非常不同的字節值(TMemoryStream)。 – 2013-04-11 14:04:31

+0

http://en.wikipedia.org/wiki/String_search – 2013-04-11 14:05:07

回答

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是一個經常忘詞,但非常有用的工具 - 比PChars中來得容易,更安全等

對於多次搜索,使用POS要麼ackwardly環,串等或使用正則表達式。

這段代碼在Delphi XE中可以正常工作,雖然TStringStream非常老舊 - 不確定它是否符合unicode。

(這個例子是有漏洞的 - 爲了簡潔起見我省略了最終代碼)

+1

在較新的Delphi版本中TStringStream.Create有一個接受TEncoding的重載:http://docwiki.embarcadero.com/Libraries/XE2/en/System.Classes.TStringStream.Create – 2013-04-16 14:39:43

相關問題