procedure Split(S: String; List: TStringList; Separator: Char);
var
P, C: PAnsiChar;
S, Buff: String;
begin
List.Clear;
if S = '' then
Exit;
List.BeginUpdate;
(* [Ajusting size - Slow *)
if S[1] = Separator then
Insert('', S, 1);
S := S + Separator;
(* Adjusting size] *)
//Get Pointer to data
P := PChar(S);
//initial position
C := P;
while P^ <> #0 do //check if reached the end of the string
begin
//when found a separator
if P^ = Separator then
begin
if P = C then //check if the slot is empty
Buff := ''
else //when it is not empty, make an string buffer
SetString(Buff, C, P-C);
List.Add(Buff); //add the string into the list
Inc(C, P-C+1); //moves the pointer C to the adress of the pointer P
end;
Inc(P); //go to next char in the string
end;
List.EndUpdate;
end;
此代碼工作正常,但移動的串3次在存儲器:
如何將字符串複製到另一個字符在第一個位置留下空白字符?
在方法調用(通過複製)
在插入(「」,S,1)
在級聯:S:= S +分隔符;
我考慮在S參數添加const關鍵字,創建內部串到更多或更少的複製數據是這樣的:
if S[1] = Separator then
begin
SetLength(Str, Length(S)+2);
//HERE!! how to copy the string
Str[1] := ' ';
end
else
begin
SetLength(Str, Length(S)+1);
//HERE!! how to copy the string
end;
//Add Separator in the last position
Str[Length(Str)] := Separator;
因此:
如果S包含「;」
它將創建一個包含2個項目('','')的字符串列表。
如果S包含'; A'
它將創建一個帶有2個項目('','A')的字符串列表。
如果S包含'A; A'
它將創建一個包含2項('A','A')的字符串列表。
如果S包含'A''
它將創建一個包含2個項目('A','')的字符串列表。
實例中使用了什麼分隔符 - ';'或空間? – MBo
我相信根本不需要移動字符串。使它成爲常量參數,並用簡單的有限自動機算法處理數據,其初始狀態取決於第一個符號。 – MBo
@MBo我不能想到一個算法,不需要修改字符串就可以做我所需要的。如果你有東西請給我看,我會欣賞 – EProgrammerNotFound