用到的函數:
function pos(Substr:string; S: string):string; //函數返回子字符串第一次出現在制定字符串中的索引值。
copy() // 復制字符串
delete() //刪除字符串中的一部分
思路:利用Pos函數定一個范圍,然后再COPY,最后刪了這個已經復制的部分,再進行下一個索引,如此循環。
例:
分下列字符串,DELPHI的:
ABCD VAR 1234
這是要拆分的一行字符串, 字符串之間有N個空格這樣子.
const
S = 'ABCD VAR 1234';
var
p: integer;
str,rs: string;
begin
rs = S;
p := Pos(' ', rs);
while(p <> 0)
begin
str := Copy(S,p,Length(rs));
Delete(S,1,p);
ListBox1.Items.Add(str);
p := Pos(' ', rs);
end;
end;
例2
在要求用戶輸入GUID后,{E22ACEBC-DBFB-4F8C-BA76-D24151ECFD52},
我想將它存入TGUID中,但StringToGUID卻不能用,那我就想將它轉換成幾個字符串,“E22ACEBC","DBFB","BA76",
uses StrUtils;
procedure StrToStrings(S: AnsiString; Sep: AnsiString; const List: TStrings);
var
I, L: Integer;
Left: AnsiString;
begin
Assert(List <> nil);
List.Clear;
L := Length(Sep);
I := Pos(Sep, S);
while (I > 0) do
begin
Left := LeftStr(S, I - 1);
List.Add(Left);
Delete(S, 1, I + L - 1);
I := Pos(Sep, S);
end;
if S <> '' then
List.Add(S);
end;