Detailed usage of tstringlist in Delphi

Source: Internet
Author: User
Tags abstract comparison sort

Tstringlist class is a pair of the most factory used in Delphi, we look at the detailed usage of tstringlist here together.

Let's start by listing several properties to be discussed:
1, CommaText
2, Delimiter & Delimitedtext
3, Names & Values & Valuefromindex

Tstrings is an abstract class that, in actual development, is the most applied except for the basic type.

Tstringlist Common Methods and properties:

Var

List:tstringlist;

I:integer;

Begin

List: = tstringlist.create;

List.add (' Strings1 '); Add

List.add (' Strings2 ');

List.exchange (0,1); Replacement

List.insert (0, ' Strings3 '); Insert

I: = List.indexof (' Strings1 '); {The first occurrence of a position}

List.sort; Sort

list.sorted: = True; {Specify sort}

List.count; Total

List.text; {Text Collection}

List.delete (0); {Delete, 0 is the first data}

List.loadfromfile (' C:\tmp.txt '); Open

List.savetofile (' C:\tmp.txt '); Save

List.clear; Empty

List.free; Release

End

Read in string

Var

List:tstringlist;

Begin

List: = tstringlist.create;

List.commatext: = ' aaa,bbb,ccc,ddd ';

Equivalent: List.text: = ' aaa ' + #13 # # + ' BBB ' + #13 # # ' + ' CCC ' + ' #13 # # ' + ' DDD ';

ShowMessage (IntToStr (List.count)); 4

ShowMessage (List[0]); Aaa

List.free;

End

Equivalent

Displacement delimiter

Var

List:tstringlist;

Begin

List: = tstringlist.create;

List.delimiter: = ' | ';

List.delimitedtext: = ' aaa|bbb|ccc|ddd ';

ShowMessage (IntToStr (List.count)); 4

ShowMessage (List[0]); Aaa

List.free;

End

A similar hash table operation method

Var

List:tstringlist;

Begin

List: = tstringlist.create;

List.add (' aaa=111 ');

List.add (' bbb=222 ');

List.add (' ccc=333 ');

List.add (' ddd=444 ');

ShowMessage (List.names[1]); Bbb

ShowMessage (list.valuefromindex[1]); 222

ShowMessage (list.values[' BBB '); 222

Valuefromindex can be assigned values:

LIST.VALUEFROMINDEX[1]: = ' 2 ';

ShowMessage (list[1]); bbb=2

Values can be assigned by:

list.values[' BBB ']: = ' 22 ';

ShowMessage (list[1]); Bbb=22

List.free;

End

Avoid duplicate values

Var

List:tstringlist;

Begin

List: = tstringlist.create;

List.add (' AAA ');

list.sorted: = True; You need to specify a sort first

List.duplicates: = Dupignore; Discard if duplicate value is found

List.add (' AAA ');

ShowMessage (List.text); Aaa

The duplicates has 3 selectable values:

Dupignore: Give up;

Dupaccept: End;

Duperror: Prompt error.

List.free;

End

Sort and Reverse sort

{Sort Function}

function Desccomparestrings (list:tstringlist; Index1, Index2:integer): Integer;

Begin

Result: =-ansicomparetext (List[index1], list[index2]);

End

Procedure Tform1.button1click (Sender:tobject);

Var

List:tstringlist;

Begin

List: = tstringlist.create;

List.add (' BBB ');

List.add (' CCC ');

List.add (' AAA ');

Not sorted

ShowMessage (List.text); BBB CCC AAA

Sort

List.sort;

ShowMessage (List.text); AAA BBB CCC

Inverted sort

List.customsort (desccomparestrings); Call sort function

ShowMessage (List.text); CCC BBB AAA

If

list.sorted: = True;

List.add (' 999 ');

List.add (' 000 ');

List.add (' zzz ');

ShowMessage (List.text); 999 AAA BBB CCC ZZZ

End

Now let's discuss some of its advanced usage.

Let's start by listing several properties to be discussed:

1, CommaText

2, Delimiter & Delimitedtext

3, Names & Values & Valuefromindex

Let's look at the first one: CommaText. How to use it. To speak in code:

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);

End

After executing this code, you can see that showmessage shows the difference: AAA BBB CCC DDD.

In other words, strs.commatext: = Constr The function of this sentence is to put a string with ', ' as the delimiter, the segment is added to the tstrings.

So what if we don't split it with ', '? Now look at the second example. Use delimiter and 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);

End

As you can see, the displayed effect is identical to the first example. Explain:

Delimiter is the delimiter, the default is: ', '. Delimitedtext is to press delimiter as a string of delimiters, to get the assignment back to the string by delimiter character to add to the tstrings.

Speaking of which, there is an attribute that reminds of QuoteChar. The default value is: ' "' (not including single quotes)

What's the use of it. See Example:

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);

End

The display is still AAA BBB CCC DDD. Why not: "AAA" "BBB" "CCC" "DDD"?

Let's look at one more example:

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);

End

Displayed is also AAA BBB CCC DDD. In contrast, it should be easy to understand. This is not much to say, not much to use.

But to say more, when delimiter for: ', ' and QuoteChar: ' ', delimitedtext and Commatext are equal.

The last three to say are: Names & Values & Valuefromindex.

Take a look at the following code:

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);

ShowMessage (STRs. Values[strs. Names]);

ShowMessage (STRs. Valuefromindex);

End

End

It is not difficult to see through this example:

At this time, the content in STRs is:

0=aaa

1=bbb

2=ccc

3=ddd

In names, it is:

0

1

2

3

In the values, it is:

Aaa

Bbb

Ccc

Ddd

===============================================================================================

Tstringlist and TList

In this chapter, we only discuss tstringlist, and Tlist in the next chapter to discuss it in detail.

The first chapter, Tstringlist

Here we have to explain tstringlist, but at the same time there is a related class can not be ignored, that is the Tstrings class

Tstringlist is derived from tstrings, and Tstrings is an abstract class that inherits from the Tpersistent class.

Therefore, we will explain the Tstrings class and the Tstringlist class together, and do the comparison

1, TStrings, Tstringlist is not a visual component, just two general class, so they are not comparable with visual components TMemo, Trichedit.

2, TStrings, tstringlist are management "string-subordinate objects" such a list, the former is an abstract class, can not be instantiated, just define some common properties, methods, and the latter is inherited from the tstringlist, you can instantiate the use. Such as:

Var
S1, s2:tstrings;
S3:tstringlist;
Begin
S1: = tstrings.create; This is not possible (because Tstrings is an abstract class, you cannot create objects directly)
S3: = tstringlist.create; This is possible.
S2: = tstringlist.create; This is also possible (the typical use of polymorphism)
End

Attention:

The declaration above S2 is the tstrings type, which is assigned to the declared Tstrings variable after the object is created by a tstringlist class. This is typical of polymorphic use. What You don't know what polymorphism is. Good-looking, this is the big shot, this is not know, quickly hungry to fill up and then come back to find a little Dragon ~ ~ ~)

I said Tstrings class is the parent class of the Tstringlist class, in polymorphic use, when a subclass object is assigned to a parent class variable, the scope (property, method) of the variable is to be noted, the property or method that the subclass does not have, the variable is not available, and the type conversion tstringlist (S2) is required Before it can be called. As in the following code snippet

Var
S:tstrings;
Begin
S: = Tstringlist.create;//tstringlist implements the abstract method in the tstrings.

S.add (' 123456789ABC '); So calling the Add method is correct;
Because there is an abstract declaration of the Add method in the Tstrings class;
It actually calls the subclass Tstringlist implementation of Add.

S.sort//And this calls the sort sorting method to make an error;
Because there is no declaration of the sort method in the Tstrings class;
The variable s is declared as the Tstrings class, so he cannot see the newly added methods and properties in the subclass.
S.free;
End

There is a method in the Tstringlist class in the code above, called sort (which is a sort of method), but not within the Tstrings class, which is the new addition to the Tstringlist subclass. Well, in the above program code snippet, if this call code s2.sort, haha, immediately you will see the compiler error, specifically why, we can think about it, or refer to the book of the master Levi read the relevant chapters.

Var
S1, s2:tstrings;
S3:tstringlist;
Begin
S1: = tstrings.create; This is not possible (because Tstrings is an abstract class, you cannot create objects directly)
S3: = tstringlist.create; This is possible.
S2: = tstringlist.create; This is also possible (the typical use of polymorphism)
S1.      ADD (' 123456789ABC '); Error, because S1 in Add is an abstract method, only the declaration
S.free;
End

Let's take a look at the S1 variable in the code above, you can declare the object of tstrings, but if you create it like above, the compiler emits a warning message, lists the abstract methods in the Tstrings class, reminds you, this is an abstract class, you should not directly create his object, Of course, if you are not afraid of death, it is necessary to compile and run the program, there is no problem, the compiler is generally a warning message is spared, so your program (as shown above) can still run.

But, hey, you see. I said, but if you use the Add,delete of the Tstrings object you created in the later code, you're dead, because these are abstract methods, they're not available, it's an abstract method.

There is no problem with S.add (' 123456789ABC ') in the second piece of code, which can be performed well, but the S1.add (' 123456789ABC ') in the third code will get an error. , their s and S1 variables are not all tstrings types.

On this issue, the Little Dragon has been point is very clear, this is a very important aspect of object-oriented programming language "polymorphism", if the reader is not clear about this concept, then a lot of things will be confused, will go a lot of detours, so, hurriedly look at the relevant information. Here we will not say, I only say: This is very important ....

3. TMemo is a common visual vcl component that is commonly used to display plain text content of multiple lines.

The Items property type in Delphi 5 is tstrings (which is actually inherited from Tstrings tmemostrings), so you can import data directly from variables of the Tstrings compatible type.

The components in Delphi 7 are changed, without the items property, instead of the lines property, the type is tstrings.

4.TRichEdit is another common visual VCL component that we typically use to display formatted text content.

The Items property type in Delphi 5 is also tstrings (which is actually inherited from Tstrings tricheditstrings), so you can import data directly from variables of the Tstrings compatible type.

The components in Delphi 7 are changed, without the items property, instead of the lines property, the type is tstrings.

5. Tstrings derived classes are primarily used to manage string collections and object collections. For example, in Delphi5, Tstringlist internally declares an array of strings and objects each to store data, whereas in Delphi7 Tstringlist is internally implemented as a record type. So they can save strings and objects at the same time (note: Generally we use tstringlist to manipulate the list of arrays, and the Tlist class to be addressed in the next chapter to manipulate the list of objects, but in fact the Tstringlist class can also handle objects, As long as the reader takes a closer look at the source code of the Tstringlist class VCL in Delpgi7, be aware that the private variable in the source is a record type.

6, generally we directly use the Tstringlist class instead of the Tstrings class, because the Tstrings class is an abstract class, can not be used directly, so below we list the Tstringlist class method, and focus on its role

Method description
Add a String Tstringlist.add (' 123456789ABC ') at the end
AddObject adds an object Tstringlist.addobject (' btn ', Button1) at the end;
Insert inserts a string at the specified position tstringlist.insert (0, ' 123456789ABC ')
InsertObject inserts a string at the specified location and assigns him a corresponding object
Example: Place the component name of all components in a form into the Item property of the ListBox

The Item property is a Tstrings type procedure Tform1.button1click (sender:tobject);
Var
I:integer;
Begin
For I: = 0 to Form1.componentcount-1 do
ListBox1.Items.InsertObject (0, Form1.components[i].name,form1.components[i] as TObject);
End

Delete Deletes a string at the specified location, and if the string is equipped with an object, the object also deletes Tstringlist.delete (' 0 ')
Clear clears the list string, and if the string has an object, the object is moved out, but the object is not freed
Exchange exchanges the position of two strings, and if the strings are equipped with objects, the objects are also exchanged tstringlist.exchange (0,1)
Find the position of a known string in the list, note that the declaration of index in the method declaration is VAR index
Tstringlist.find (const s:string; var index:integer): Boolean;
IndexOf Unlike find, IndexOf is used to find the location specified by a string
Tstringlist.indexof (const s:string): Integer;
Sort sorts, the sorted property is set to False when you call sort sort;
Sorted property
When the sorted property is set to False, call sort sort;
When the sorted property is set to True, the list is automatically sorted, then the insert is not used, but the add is used, and the system is automatically sorted;
Customsort Customer Custom Sort, this we do not introduce, interested to see Delphi help
CaseSensitive set string comparison, take position, case sensitivity, this we do not introduce, interested in seeing Delphi help
Duplicates add string, whether to allow repeating field add, this we do not introduce, interested in seeing Delphi help

Tstringlist Common Methods and properties:
Var
List:tstringlist;
I:integer;
Begin
List: = tstringlist.create;
List.add (' Strings1 '); Add
List.add (' Strings2 ');
List.exchange (0,1); Replacement
List.insert (0, ' Strings3 '); Insert
I: = List.indexof (' Strings1 '); {The first occurrence of a position}
List.sort; Sort
list.sorted: = True; {Specify sort}
List.count; Total
List.text; {Text Collection}
List.delete (0); {Delete, 0 is the first data}
List.loadfromfile (' C:\tmp.txt '); Open
List.savetofile (' C:\tmp.txt '); Save
List.clear; Empty
List.free; Release
End
--------------------------------------------------------------------------------

Other:

Tstringlist has a small bug delimiter The space is also used as the delimiter problem

It will use a space as a delimiter.  
example  
List.delimiter: = ' | ';  
List.delimitedtext: = ' aaa|bb b|ccc|ddd ';  
//BBB If there is a space, its count is 5 instead of 4 
And Splitcolumns is a function in Idstrings.pas,  
It fixes the problem of tstrings.delimitedtext and tstrings.delimiter separating spaces as separators  
splitcolumns 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.