读书人

Delphi有这么的函数吗

发布时间: 2013-09-28 10:01:20 作者: rapoo

Delphi有这样的函数吗?
已有类似这样的字符串(形式可以更改) 123|ZXC|5697|QWERRT|
已有这样的全局变量A,B,C,D:string;
请问delphi有函数能一次性把4段字符串分配给4个变量吗?
[解决办法]
没有,要自己写
VAR
iStr:TStringList;
A,B,C:String;
Const
s='123
[解决办法]
ZXC
[解决办法]
5697
[解决办法]
QWERRT
[解决办法]
';
Begin
iStr:=TStringList.Create;
Try
//转换成TStringList格式
iStr.text:=AnsiReplaceText(s,'
[解决办法]
',#$d#$a);//uses StrUtils;
A:=iStr.strings[0];
B:=iStr.strings[1];
C:=iStr.strings[2];
finally
FreeAndNil(iStr);
End;
End;
[解决办法]
with TStringList.Create do
begin
Delimiter := '
[解决办法]
';
DelimitedText := '123
[解决办法]
ZXC
[解决办法]
5697
[解决办法]
QWERRT
[解决办法]
';
A := Strings[0];
B := Strings[1];
C := Strings[2];
D := Strings[3];
Free
end;
[解决办法]


//用SplitChar分割字符串,结果保存于apsDest的字符串指针中,apsDest必须是字符串指针数组
//使用方法:SplitString('11
[解决办法]
22
[解决办法]
33
[解决办法]
44
[解决办法]
' , '
[解决办法]
' , [@S1 , @S2 , @S3....]);
//可以带多个字符串到数组中
procedure SplitString(Const S : String; SplitChar : Char; Const apsDest : array of Const);
var
i , index , sStart : integer;
P : PChar;
begin
for i:=0 to High(apsDest) do PString(apsDest[i].VPointer)^ := '';
if (S='') or (Length(apsDest)=0) then exit;
P := Pointer(S);
index := 0;
sStart := 1;
for i:=1 to Length(S) do begin
if P[i-1] = SplitChar then begin
PString(apsDest[index].VPointer)^ := Copy(S , sStart , i-sStart);
sStart := i + 1;
inc(index);
if index>High(apsDest) then exit;
end;
end;
if index<=High(apsDest) then
PString(apsDest[index].VPointer)^ := Copy(S , sStart , Length(S));
end;


//使用例子:
procedure TForm1.FormCreate(Sender: TObject);
var
S1 , S2 , S3 , S4 , S5 : String;
begin
//需要分割成几个,就带几个字符串的地址
SplitString('123
[解决办法]
ZXC
[解决办法]
5697
[解决办法]
QWERRT
[解决办法]
' , '
[解决办法]
' , [@S1 , @S2 , @S3 , @S4]);
Caption := S1;

//或者
SplitString('123
[解决办法]


ZXC
[解决办法]
5697
[解决办法]
QWERRT
[解决办法]
' , '
[解决办法]
' , [@S1 , @S2 , @S3 , @S4 , @S5]);
//...
end;

读书人网 >.NET

热点推荐