您现在的位置:首页 >> VCL >> VCL >> 内容

Delphi总结使用TStrings的一些技巧

时间:2011/9/3 16:25:39 点击:

  核心提示:先把要讨论的几个属性列出来:1、CommaText2、DelimiterDelimitedText3、NamesValuesValueFromIndex 先看第一个:CommaText。怎么用呢?用代...
先把要讨论的几个属性列出来:
1、CommaText
2、Delimiter & DelimitedText
3、Names & Values & ValueFromIndex

先看第一个:CommaText。怎么用呢?用代码说话:
const
  constr :String = 'aaa,bbb,ccc,ddd';
var
  strs :TStrings;
  i :Integer;
begin
  strs := TStringList.Create;
  strs.CommaText := constr;
  for i := 0 to Strs.Count-1 do
    ShowMessage(Strs[i]);
end;
执行了这段代码后,可以看到ShowMessage显示出来的分别是:aaa bbb ccc ddd。
也就是说,strs.CommaText := constr这一句的作用,就是把一个字符串以'',''为分割符,分段添加到TStrings中。
那么如果不是以'',''来分割,又该怎么做呢?现在看第二个例子。使用Delimiter和DelimitedText。
const
  constr :String = 'aaa\bbb\ccc\ddd';
var
  strs :TStrings;
  i :Integer;
begin
  strs := TStringList.Create;
  strs.Delimiter := '\';
  strs.DelimitedText := constr;
  for i := 0 to Strs.Count-1 do
    ShowMessage(Strs[i]);
end;
可以看到, 显示的效果和第一个例子是一模一样的。解释一下:
Delimiter为分隔符,默认为:'',''。DelimitedText就是按Delimiter为分隔符的一个串,得到赋值后回把这个字符串按Delimiter的字符添加到TStrings中。
说到这里,有想起一个属性,QuoteChar。其默认值为:''"''(不包括单引号)
有何用呢?看例子:
const
  constr :String = '"aaa"\"bbb"\"ccc"\"ddd"';
var
  strs :TStrings;
  i :Integer;
begin
  strs := TStringList.Create;
  strs.Delimiter := '\';
  strs.DelimitedText := constr;
  for i := 0 to Strs.Count-1 do
    ShowMessage(Strs[i]);
end;
显示出来的仍然是aaa bbb ccc ddd。为什么不是:"aaa" "bbb" "ccc" "ddd"呢?
再来看一个例子:
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
这几个属性用来处理ini文件是非常好用的。
另外说一句,在Delphi6下似乎没有ValueFromIndex这个属性

作者:网络 来源:转载
共有评论 3相关评论
发表我的评论
  • 大名:
  • 内容:
本类推荐
  • 没有
本类固顶
  • 没有
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号