Delphi中的split函数
procedure TForm1.Button1Click(Sender: TObject);
var
s1:TStringList;
begin
s1:=split('11111111:2222:33333:44444',':');
Memo1.Lines.AddStrings(s1);
s1.Free;
end;function split(s,s1:string):TStringList;
begin
Result:=TStringList.Create;
while Pos(s1,s)>0 do
begin
Result.Add(Copy(s,1,Pos(s1,s)-1));
Delete(s,1,Pos(s1,s));
end;
Result.Add(s);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
s1:TStringList;
begin
s1:=split('11111111:2222:33333:44444',':');
Memo1.Lines.AddStrings(s1);
s1.Free;
end;
一、直接使用如下函数(注:ch只能是单字符,如键盘上英文状态下的字符)
function SplitString(const Source,ch:String):TStringList;
var
temp:String;
i:Integer;
begin
Result:=TStringList.Create;
//如果是空自符串则返回空列表
if Source=''
then exit;
temp:=Source;
i:=pos(ch,Source);
while i<>0 do
begin
Result.add(copy(temp,0,i-1));
Delete(temp,1,i);
i:=pos(ch,temp);
end;
Result.add(temp);
end;
二、直接使用TStringList
procedure TForm1.Button3Click(Sender: TObject);
var
Str:String;
ResultList:TStringList;
I:Integer;
begin
str:= '南京~信息~工程~大学';
ResultList := TStringList.Create;
try
ResultList.Delimiter := '~';
ResultList.DelimitedText := str;
for I:= 0 to ResultList.Count-1 do
begin
Memo1.Lines.Add(ResultList.Strings[I]);
end;
finally
FreeAndNil(ResultList);
end;
end;
三、支持特殊字符版(ch可以为字符串,如'aa')
function SplitString(const Source,ch:String):TStringList;
var
Temp:String;
I:Integer;
chLength:Integer;
begin
Result:=TStringList.Create;
//如果是空自符串则返回空列表
if Source='' then Exit;
Temp:=Source;
I:=Pos(ch,Source);
chLength := Length(ch);
while I<>0 do
begin
Result.Add(Copy(Temp,0,I-chLength+1));
Delete(Temp,1,I-1 + chLength);
I:=pos(ch,Temp);
end;
Result.add(Temp);
end;
关键字词: