Delphi中的字符串分割
今天偶尔要做的Delphi程序,其中涉及到了字符串处理,里面有一个功能类似于VB里的split()函数的功能,于是查了很久才查到些资料,现将这些资料整理一下,方便大家.
首先是一个网友自己编的函数.实现了和split()函数的功能.
?unit Unit1;
interface
uses
? Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
? Dialogs, StdCtrls;
type userarray=array of string;
type
? TForm1 = class(TForm)
??? Edit1: TEdit;
??? Button1: TButton;
??? procedure Button1Click(Sender: TObject);
? private
??? function split(s: string; dot: char): userarray;
??? { Private declarations }
? public
??? { Public declarations }
? end;
var
? Form1: TForm1;
implementation
uses StrUtils;
{$R *.dfm}
//按所给字符将字符串分隔成数组
function TForm1.split(s:string;dot:char):userarray;
var
str:userarray;
i,j:integer;
begin
i:=1;
j:=0;
SetLength(str, 255);
while Pos(dot, s) > 0 do??? //Pos返回子串在父串中第一次出现的位置.
begin
str[j]:=copy(s,i,pos(dot,s)-i);
i:=pos(dot,s)+1;
s[i-1] := chr(ord(dot)+1);
j:=j+1;
end;
str[j]:=copy(s,i,strlen(pchar(s))-i+1);
result:=str;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
? ur:userarray;
? i:Integer;
begin
? ur:=split(Edit1.Text,';');
? for i :=0 to 255 do
? begin
??? if length(ur[i])=0 then Exit;
??? ShowMessage(ur[i]);
? end;
end;
end.
说明,测试这个代码时请在窗体上放一个文本编辑框和一个按钮,字符串是以';'号分割的;
第二种方法比较简单:
再来看一个例子:const
? constr :String = '|aaa|\|bbb|\|ccc|\|ddd|';
var
? strs :TStrings;
? i :Integer;
begin
? strs := TStringList.Create;
? strs.Delimiter := '\';
? strs.QuoteChar := '|';
? strs.DelimitedText := constr;
? for i := 0 to Strs.Count-1 do
??? ShowMessage(Strs[i]);
end;
显示出来的又是aaa bbb ccc ddd。对比一下,应该不难明白吧?这个就不多说了,用得也不多。
但是还要多说一句,当Delimiter为:','而QuoteChar为:'"'时,DelimitedText和CommaText是同等的。
最后要说的三个是:Names & Values & ValueFromIndex。
看看下面的代码:
const
? constr :String = '0=aaa,1=bbb,2=ccc,3=ddd';
var
? strs :TStrings;
? i :Integer;
begin
? strs := TStringList.Create;
? strs.CommaText := constr;
? for i := 0 to strs.Count-1 do
? begin
??? ShowMessage(strs.Names[i]);
??? ShowMessage(strs.Values[strs.Names[i]]);
??? ShowMessage(strs.ValueFromIndex[i]);
? end;
end;
通过这个例子不难看出:
这个时候strs中的内容是:
0=aaa
1=bbb
2=ccc
3=ddd
而Names中则是:
0
1
2
3
在Values中则是:
aaa
bbb
ccc
ddd?
http://blog.csdn.net/mc1035/archive/2007/05/16/1611214.aspx