Usage of Stringlist split string in Delphi
Tstrings is an abstract class that, in actual development, is the most applied except for the basic type.
General usage We all know, now to discuss some of its advanced usage.
1, CommaText
2, Delimiter &delimitedtext
3, Names &values &valuefromindex
Let's look at the first one: CommaText. How to use it?
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
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 add a string with a ', ' as a delimiter, and fragment to 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[i]);
End
As you can see, the displayed effect is identical to the first example. Explain:
Delimiter is the delimiter, the default is: ', '. Delimitedtext is a string that is delimited by delimiter.
After the assignment, the string is added to the tstrings by the delimiter character.
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[i]);
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[i]);
End
Displayed is also AAA BBB CCC DDD. It should be easy to compare, you know? This is not much to say, not much to use.
But one more word, when delimiter is: ', ' and QuoteChar: ' ',
Delimitedtext and Commatext are the same.
The last three to say is: 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[i]);
ShowMessage (STRs. Values[strs. Names[i]]);
ShowMessage (STRs. Valuefromindex[i]);
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
Usage of Stringlist split string in Delphi