Difference between revisions of "TStringList-TStrings Tutorial/fr"
Line 41: | Line 41: | ||
===Exemple étendu=== | ===Exemple étendu=== | ||
− | + | Que diriez-vous d'un exemple plus juteux, hein? | |
<syntaxhighlight> | <syntaxhighlight> | ||
Line 59: | Line 59: | ||
Writeln('Enter a string to add'); | Writeln('Enter a string to add'); | ||
Readln(S); | Readln(S); | ||
− | if (S = 'EXIT') then Halt; //Halt | + | if (S = 'EXIT') then Halt; //Halt arrête immédiatement l'exécution |
− | // | + | // Si vous observez de près, vous verrez que cela mène à une fuite de mémoire. |
if (S <> '') then | if (S <> '') then | ||
begin | begin | ||
Counter := Str.Add(S); | Counter := Str.Add(S); | ||
− | Writeln('String: ' + S + ' | + | Writeln('String: ' + S + ' a été ajoutée!'); |
− | Writeln(' | + | Writeln('L''index est: ' + IntToStr(Counter)); // Le compteur sera toujours l'index de la dernière chose ajoutée |
end | end | ||
else | else | ||
begin | begin | ||
− | Writeln(' | + | Writeln('Aucune donnée saisie...'); |
end; | end; | ||
until (S = 'EXIT'); | until (S = 'EXIT'); | ||
− | writeln(' | + | writeln('Contenus: '+ Str.CommaText); |
− | Str.Free; // | + | Str.Free; //Libère la mémoire |
end. | end. | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Néanmoins, pour éviter une possible fuite de mémoire, vous devriez toujours utiliser un bloc try - finally là où c'est possible, pour ceci, vous devez faire quelque chose comme: | |
<syntaxhighlight> | <syntaxhighlight> | ||
Line 88: | Line 88: | ||
try | try | ||
... | ... | ||
− | // | + | // faire des choses avec votre stringlist |
... | ... | ||
finally | finally |
Revision as of 20:24, 10 July 2014
│
Deutsch (de) │
English (en) │
español (es) │
suomi (fi) │
français (fr) │
polski (pl) │
русский (ru) │
TStringList
La classe TStringList (ou sa mère TStrings) est un peu comme un fantastique tableau dynamique ou un ensemble de chaînes (un ensemble de chaîne n'est pas possible dans FPC). Il va devenir très pratique en programmant et je vais vous apprendre un usage basique de la TStringList.
Exemple simple
program StrList;
{$mode objfpc}
uses
Classes, SysUtils;
var
Str: TStringList;
begin
Str := TStringList.Create; // C'est nécessaire pour utiliser cette classe (enfin toutes les classes)
try
Str.Add('Some String!');
writeln('The stringlist now has ' + IntToStr(Str.Count) + ' string(s).');
Readln;
finally
Str.Free; //Libère la mémoire utilisée par l'instance
end;
end.
C'est un simple exemple de programme console qui créera uns TSTringListe et y ajoutera une chaîne. Maintenant, il y a des choses que vous devez savoir:
Create - Créera le la liste de chaîne, vide. Si vous utilisez Create, vous devrez plus tard faire Free pour libérer la mémoire occupée. Sinon, votre programme ne plantera pas mais toute la mémoire qu'il occupe ne sera pas restituée, ce qu'on appelle une fuite de mémoire.
Count - Cette propriété est un compteur pour le nombre de chaînes dans la liste.
Add - Cette méthode vous permet d'ajouter une chaîne dans la StringList. C'est une fonction qui vous retournera l'Index de la chaîne. C'est là que le compteur est très pratique.
Delete - Supprimera une chaîne une chaîne de la StringList. Il faut juste savoir que vous devez entrer l'index de la chaîne et non la chaine elle-même. Je l'ai déjà dit : c'est comme un fantastique tableau dynamique.
IndexOf - retournera l'index d'une chaîne dans la liste. Si elle n'y est pas trouvée, la fonction retournera -1.
Clear - Videra la liste (elle ne contient plus aucune chaîne).
Exemple étendu
Que diriez-vous d'un exemple plus juteux, hein?
program StrList2;
{$mode ObjFPC}
uses
Classes, SysUtils;
var
Str: TStringList;
S: String;
Counter: Integer;
begin
Str := TStringList.Create;
Writeln('String List Test');
repeat
Writeln('Enter a string to add');
Readln(S);
if (S = 'EXIT') then Halt; //Halt arrête immédiatement l'exécution
// Si vous observez de près, vous verrez que cela mène à une fuite de mémoire.
if (S <> '') then
begin
Counter := Str.Add(S);
Writeln('String: ' + S + ' a été ajoutée!');
Writeln('L''index est: ' + IntToStr(Counter)); // Le compteur sera toujours l'index de la dernière chose ajoutée
end
else
begin
Writeln('Aucune donnée saisie...');
end;
until (S = 'EXIT');
writeln('Contenus: '+ Str.CommaText);
Str.Free; //Libère la mémoire
end.
Néanmoins, pour éviter une possible fuite de mémoire, vous devriez toujours utiliser un bloc try - finally là où c'est possible, pour ceci, vous devez faire quelque chose comme:
var
slist: TStringList;
...
slist := TStringList.Create;
try
...
// faire des choses avec votre stringlist
...
finally
if Assigned(slist) then
FreeAndNil(slist);
end;
File Handling
When using the TStringList you have 2 file handling procedures: SaveToFile and LoadFromFile. SavetoFile will save all strings in the list to a file. LoadFromFile will open the file and add the file data to the list string by string.
program StrListFile;
{$mode objfpc}
uses
Classes, SysUtils;
var
Str: TStringList;
begin
Str := TStringList.Create;
try
Str.LoadFromFile('SomeFile.txt');
Str.Add('Hello');
Str.SaveToFile('SomeFile.txt');
finally
Str.Free;
end;
end.
You just opened a file, edited it and saved it right back to were it was!
Dynamic string array comparison
TStringList is simply an object-oriented version of a dynamic string array. Some methods have analogs:
Operation | array of string | TStringList |
---|---|---|
Variable declaration | StringList: array of string; | StringList: TStringList; |
Initialization | implicit constructor | StringList := TStringList.Create |
Set size | SetLength(StringList, X); | StringList.Size := X; |
Get size | X := Length(StringList); | X := StringList.Count; |
Add item | SetLength(StringList, Length(StringList) + 1); StringList[Length(StringList) - 1] := X; | StringList.Add(X); |
Delete item | for I := Index to Length(StringList) - 2 do StringList[I] := StringList[I + 1]; SetLength(StringList, Length(StringList) - 1); | StringList.Delete(Index); |
Remove all items | SetLength(StringList, 0); | StringList.Clear; |
Finalization | implicit destructor | StringList.Free; |
However, TStringList offers much more functionality than a basic structure such as a dynamic array.
Keep Learning
TStringList has many other interesting features:
- It allows you to sort the strings
- It allows you to limit the list to only unique strings
- You can get the text of all strings as a single string using the Text property.
- You can store an object or other data next to the string
You can learn all the different procedures, functions and properties. See TStringList documentation... or the help in Lazarus.
... and you might like to extend this tutorial if you feel like it.