我正在嘗試創建一個類似于 Delphi 的pos函式的函式,但我可以傳遞不同的字串進行搜索,而不僅僅是一個。所以我可以這樣呼叫函式:
multipos('word1#word2#word3','this is a sample text with word2',false);
// will return 'word2'
該函式將回傳找到的字串。
我做的代碼在下面,它正在作業,但它太慢了。我怎樣才能提高這段代碼的速度?
function multipos(needles,key: string; requireAll: boolean): string;
var
k: array [1 .. 50] of string;
i, j: integer;
r, aux: string;
flag: boolean;
begin
if trim(key) = '' then
Result := ''
else
try
r := '';
Result := '';
j := 1;
for i := 1 to 50 do
k[i] := '';
for i := 1 to length(needles) do
begin
if needles[i] <> '#' then
aux := aux needles[i]
else
begin
k[j] := aux;
Inc(j);
aux := '';
end;
if j >= 50 then
break;
end;
if aux <> '' then
k[j] := aux;
for i := 1 to j do
begin
if k[i] = '' then
break
else
if pos(lowercase(k[i]), lowercase(key)) > 0 then
begin
if not requireAll then
begin
Result := k[i];
break;
end
else
begin
r := r k[i] ',';
flag := i = j;
if not flag then
flag := k[i 1] = '';
if flag then
begin
Result := r;
end;
end;
end
else
if requireAll then
begin
break;
end;
end;
except
on e: exception do
begin
Result := '';
end;
end;
end;
uj5u.com熱心網友回復:
考慮將專案作為陣列傳遞,例如:
function Multipos(A: array of string; const S: string): string;
begin
for var E in A do
if Pos(E, S) > 0 then
Exit(E);
Result := ''; // Nothing found
end;
// sample call
Multipos(['word1', 'word2', 'word3'], 'this is a sample text with word2');`
要實作 RequireAll 功能,請在第一次失敗時停止。只需檢查在這種情況下要回傳的內容。
此外,TStrings/TStringList 可以滿足您的需求。檢查它的Delimiter和 DelimitedText 屬性。
uj5u.com熱心網友回復:
由于您沒有指定 Delphi 版本,我只是假設最新版本:
function multipos(const needles,key: string; requireAll: boolean): string;
var
lst: TStringList;
begin
lst := TStringList.Create;
try
var lowerkey := key.ToLower; // do this only once
for var needle in needles.Split(['#']) do begin
if lowerkey.Contains(needle.ToLower) then begin
if not requireAll then
Exit(needle);
lst.Add(needle);
end;
end;
Result := lst.CommaText;
finally
lst.Free;
end;
end;
uj5u.com熱心網友回復:
Marcodor 的陣列解決方案很好。這是一個 TStringList 替代方案:
function multipos(SubStrs: TStringList; Str: string; RequireAll: Boolean): string;
var
i: Integer;
begin
if (not Str.IsEmpty) and (not SubStrs.Count < 1) then
begin
Result := '';
for i := 0 to SubStrs.Count - 1 do
if Pos(SubStrs[i], Str) > 0 then
Result := Result Copy(Str, Pos(SubStrs[i], Str), SubStrs[i].Length)
else if RequireAll then
Result := '';
end;
end;
var
myList: TStringList;
begin
myList := TStringList.Create;
myList.Delimiter := '#';
myList.DelimitedText := 'word1#word2#word3';
Writeln(multipos(myList, 'this word1is a sample word3 text with word2', False));
end.
顯然,您需要用于 StringList 的 system.classes。也許在訪問引數之前檢查一切是否正常,但它適用于 RequireAll True 和 False。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/465479.html
標籤:德尔福
上一篇:將整數從字串保存到向量
