TStringList 常用方法与属性: 2 var
3 List: TStringList;
4 i: Integer;
5 begin
6 List := TStringList.Create;
7 List.Add('Strings1'); {添加}
8 List.Add('Strings2');
9 List.Exchange(0,1); {置换}
10 List.Insert(0,'Strings3'); {插入}
11 i := List.IndexOf('Strings1'); {第一次出现的位置}
12 List.Sort; {排序}
13 List.Sorted := True; {指定排序}
14 List.Count; {总数}
15 List.Text; {文本集合}
16 List.Delete(0); {删除, 0是第一个数据}
17 List.LoadFromFile('c:/tmp.txt');{打开}
18 List.SaveToFile('c:/tmp.txt'); {保存}
19 List.Clear; {清空}
20 List.Free; {释放}
21 end;
22
23 //读入字符串
24 var
25 List: TStringList;
26 begin
27 List := TStringList.Create;
28 List.CommaText := 'aaa,bbb,ccc,ddd';
29 //相当于: List.Text := 'aaa' + #13#10 + 'bbb' + #13#10' + 'ccc' + '#13#10' + 'ddd';
30
31 ShowMessage(IntToStr(List.Count)); //4
32 ShowMessage(List[0]); //aaa
33
34 List.Free;
35 end;
36
37 //置换分隔符
38 var
39 List: TStringList;
40 begin
41 List := TStringList.Create;
42 List.Delimiter := '|';
43 List.DelimitedText := 'aaa|bbb|ccc|ddd';
44
45 ShowMessage(IntToStr(List.Count)); //4
46 ShowMessage(List[0]); //aaa
47
48 List.Free;
49 end;
50
51
52 //类似的哈希表操作法
53 var
54 List: TStringList;
55 begin
56 List := TStringList.Create;
57
58 List.Add('aaa=111');
59 List.Add('bbb=222');
60 List.Add('ccc=333');
61 List.Add('ddd=444');
62
63 ShowMessage(List.Names[1]); //bbb
64 ShowMessage(List.ValueFromIndex[1]); //222
65 ShowMessage(List.Values['bbb']); //222
66
67 //ValueFromIndex 可以赋值:
68 List.ValueFromIndex[1] := '2';
69 ShowMessage(List[1]); //bbb=2
70
71 //可以通过 Values 赋值:
72 List.Values['bbb'] := '22';
73 ShowMessage(List[1]); //bbb=22
74
75 List.Free;
76 end;
77
78 //避免重复值
79 var
80 List: TStringList;
81 begin
82 List := TStringList.Create;
83
84 List.Add('aaa');
85
86 List.Sorted := True; //需要先指定排序
87 List.Duplicates := dupIgnore; //如有重复值则放弃
88
89 List.Add('aaa');
90
91 ShowMessage(List.Text); //aaa
92
93 //Duplicates 有3个可选值:
94 //dupIgnore: 放弃;
95 //dupAccept: 结束;
96 //dupError: 提示错误.
97
98 List.Free;
99 end;
100
101 //排序与倒排序
102 {排序函数}
103 function DescCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
104 begin
105 Result := -AnsiCompareText(List[Index1], List[Index2]);
106 end;
107
108 procedure TForm1.Button1Click(Sender: TObject);
109 var
110 List: TStringList;
111 begin
112 List := TStringList.Create;
113
114 List.Add('bbb');
115 List.Add('ccc');
116 List.Add('aaa');
117
118 //未排序
119 ShowMessage(List.Text); //bbb ccc aaa
120
121 //排序
122 List.Sort;
123 ShowMessage(List.Text); //aaa bbb ccc
124
125 //倒排序
126 List.CustomSort(DescCompareStrings); //调用排序函数
127 ShowMessage(List.Text); //ccc bbb aaa
128
129 //假如:
130 List.Sorted := True;
131 List.Add('999');
132 List.Add('000');
133 List.Add('zzz');
134 ShowMessage(List.Text); //000 999 aaa bbb ccc zzz
135 end;
标签:常用,aaa,TStringList,List,bbb,Add,ShowMessage,属性
From: https://blog.51cto.com/u_16241767/7295499