10.2. Métodos
~TStrings
Destructor.
Add
Añadir una cadena al final de la lista. El método Add retorna el índice de la nueva cadena.
virtual int __fastcall Add(const System::AnsiString S);
BeginUpdate and EndUpdate should always be used in conjunction with a try...catch statement to ensure that EndUpdate is called if an exception occurs. A block that uses BeginUpdate and EndUpdate typically looks like this:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ListBox1->Items->BeginUpdate();
try{
ListBox1->Items->Clear();
ListBox1->Items->Add("Some foo");
ListBox1->Items->Add("Some data");
ListBox1->Items->EndUpdate();
}
catch(...){
ListBox1->Items->EndUpdate(); //Executed even in case of an exception
throw;
}
}
AddObject
Añadir una cadena a la lista, y asocia un objeto a la cadena.
virtual int __fastcall AddObject(const System::AnsiString S, System::TObject* AObject);
Description
Call AddObject to add a string and its associated object to the list. AddObject returns the index of the new string and object.
This code adds the string 'Orange' and a bitmap of an orange to an owner-draw list box:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TIcon* Icon;
Icon = new TIcon;
Icon->LoadFromFile("ORANGE.ICO");
ListBox1->Items->AddObject("Orange", Icon);
}
AddStrings
Añade un grupo de cadenas a la lista. Por ejemplo, copia el contenido de un Memo en otro.
virtual void __fastcall AddStrings(TStrings* Strings);
Description
Call AddStrings to add the strings from another TStrings object to the list. If both the source and destination TStrings objects support objects associated with their strings, references to the associated objects will be added as well.
This code adds the list of strings contained in ListBox1->Items to the end of the ListBox2->Items list of strings:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ListBox2->Items->AddStrings(ListBox1->Items);
}
Append
Añade la cadena S a la lista. El método Append es igual que Add, con la excepción de que éste no retorna nigún valor.
void __fastcall Append(const System::AnsiString S);
Description
Use Append when there is no need to know the index of the string after it has been added, or with descendants of TStrings for which the index returned is not meaningful.
For example, the TStrings descendant used by memo objects uses an index to determine where to insert a string, but the inserted string does not necessarily end up as a single string in the list. Part of the inserted text may become part of the previous string, and part may be broken off into a subsequent string. The index returned by Add is not meaningful in this case.
Use Append rather than Add as a parameter for a function requiring a TGetStrProc.
This code uses a button and a list box on a form. When the user clicks the button, the code appends a new string to a list box.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ListBox1->Items->Append("New String");
}
Assign
Este método copia las cadenas contenidas en la lista del objeto TString a otro objeto. Se sobre escribe el contenido.
virtual void __fastcall Assign(TPersistent* Source);
Description
Use Assign to set the value of the TStrings object from another object. If Source is of type TStrings, the list is set to the list of the source TStrings object, and if associated objects are supported, any associated objects are copied from the Source as well.
If Source is not of type TStrings, the inherited Assign will set the value of the list from any object that supports TStrings in its AssignTo method.
This example consists of a form with a memo and listbox. When the button is clicked, the contents of the memo are filled with the contents of the listbox.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Memo1->Lines->Assign(ListBox1->Items);
}
BeginUpdate
Enables the TStrings object to track when the list of strings is changing.
void __fastcall BeginUpdate(void);
Description
BeginUpdate is called automatically by any property or method that changes the list of strings. Once the changes are complete, the property or method calls EndUpdate. Call BeginUpdate before directly modifying the strings in the list, and EndUpdate after. When implementing properties or methods that change the list in descendants of TStrings, call BeginUpdate before the changes are made, and EndUpdate when the changes are complete.
TStrings simply keeps track of when the list of strings is being changed. Some descendants of TStrings use this information to perform certain actions, such as telling a control to repaint, when updates are complete.
BeginUpdate and EndUpdate should always be used in conjunction with a try...catch statement to ensure that EndUpdate is called if an exception occurs. A block that uses BeginUpdate and EndUpdate typically looks like this:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ListBox1->Items->BeginUpdate();
try{
ListBox1->Items->Clear();
ListBox1->Items->Add("Some foo");
ListBox1->Items->Add("Some data");
ListBox1->Items->EndUpdate();
}
catch(...){
ListBox1->Items->EndUpdate(); //Executed even in case of an exception
throw;
}
}
Clear
Vacía la lista y los objetos asociados.
virtual void __fastcall Clear(void) = 0;
Description
Descendants of TStrings implement a Clear method to delete all the strings in the list, and to remove any references to associated objects.
This example fills the list of a combo box with the set of available fonts when the user drops down the list. The list is regenerated every time the list is dropped down, so if the application adds or removes fonts, the combo box stays current.
void __fastcall Form1::ComboBox1DropDown(TObject *Sender)
{
FontCombo->Items->BeginUpdate(); // prevent repaints until done
FontCombo->Items->Clear(); // empty the list of any old values
FontCombo->Sorted = true; // make sure the font names are sorted
FontCombo->Items = Screen->Fonts; // add the current list of fonts
FontCombo->Items->EndUpdate(); //reenable painting
}
Delete
Borra una cadena de la lista indicando el índice.
virtual void __fastcall Delete(int Index) = 0;
Description
Descendants of TStrings implement a Delete method to remove a specified string from the list. If an object is associated with the string, the reference to the object is removed as well. Index gives the position of the string, where 0 is the first string, 1 is the second string, and so on.
This example uses a list box and a button on a form. When the form appears, five items are in the list box. When the user clicks the button, the second item in the list box is deleted:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ListBox1->Items->Delete(1);
}
EndUpdate
Enables the TStrings object to keep track of when the list of strings has finished changing.
void __fastcall EndUpdate(void);
Description
EndUpdate is called automatically by any property or method that changes the list of strings. Call BeginUpdate before directly modifying the strings in the list, and EndUpdate after. When implementing properties or methods that change the list in descendants of TStrings, call BeginUpdate before the changes are made, and EndUpdate when the changes are complete.
TStrings simply keeps track of when the list of strings is being changed. Some descendants of TStrings use this information to perform certain actions, such as telling a control to repaint, when updates are complete.
Equals
Compara la lista de cadenas contenidas en la lista con otros objetos TStrins y retorna true si las dos listas son iguales.
bool __fastcall Equals(TStrings* Strings);
Description
Call Equals to compare the lists in two TStrings objects. Equals compares only the strings, not any references to associated objects. Equals returns true if the lists for both TStrings objects have the same number of strings and the strings in each list are identical. Equals returns false if the lists are different in length, if they contain different strings, or if the order of the strings in the two lists differ.
Exchange
Intercambia la posición de dos cadenas en la lista.
virtual void __fastcall Exchange(int Index1, int Index2);
Description
Call Exchange to rearrange the strings in the list. The strings are specified by their index values in the Index1 and Index2 parameters. Indexes are zero-based, so the first string in the list has an index value of 0, the second has an index value of 1, and so on.
If either string has an associated object, Exchange changes the position of the object as well.
GetText
Asigna un buffer de texto y lo llena con el valor de la propiedad Text.
virtual char * __fastcall GetText(void);
Description
Call GetText to obtain a dynamically allocated character buffer containing all of the strings in the list. Individual strings are separated by a carriage return and line feed. The caller is responsible for freeing the returned value.
Ejemplo:
String dato;
Dato=Memo1->Lines->GetText(); //Entrega todas las líneas separadas por retorno de carro y avance de línea
IndexOf
Retorna la posición de una cadena en la lista. El texto ha de coincidir con toda la línea.
virtual int __fastcall IndexOf(const System::AnsiString S);
if(Memo1->Lines->IndexOf("Win.ini")>-1);
Description
Call IndexOf to obtain the position of the first occurrence of the string S. IndexOf returns the 0-based index of the string. Thus, if S matches the first string in the list, IndexOf returns 0, if S is the second string, IndexOf returns 1, and so on. If the string is not in the string list, IndexOf returns -1.
Note: If the string appears in the list more than once, IndexOf returns the position of the first occurrence.
This example uses a file list box, a directory list box, and a label on a form. When the user uses the directory list box to change directories, a message appears and the color of the form changes if the file AUTOEXEC.BAT is in the new directory. The code is written in the OnChange event of the directory list box:
void __fastcall TForm1::DirectoryListBox1Change(TObject *Sender)
{
FileListBox1->Directory = DirectoryListBox1->Directory;
if (FileListBox1->Items->IndexOf("AUTOEXEC.BAT") > -1) {
Color = clYellow;
Label1->Caption = "You are in the root directory!";
}
}
IndexOfName
Retorna la posición de la primera cadena con la forma Nombre=Valor con el nombre especifífico.
int __fastcall IndexOfName(const System::AnsiString Name);
pos=Memo1->Lines->IndexOfName("Variable3"); //Retorna el número de línea
Description
Call IndexOfName to locate the first occurrence of a string with the form Name=Value where the name part is equal to the Name parameter. IndexOfName returns the 0-based index of the string. If no string in the list has the indicated name, IndexOfName returns -1.
Strings of the form Name=Value are commonly found in .INI files. For example, here are a few strings taken from a typical .INI file:
DisplayGrid=1
SnapToGrid=1
GridSizeX=8
GridSizeY=8
The strings that make up the Params property of a database component (TDatabase) have this format as well.
The Name that identifies the string is to the left of the equal sign (=), and the current Value of the Name identifier is on the right side. There should be no spaces present before or after the equal sign.
Note: If there is more than one string with a name portion matching the Name parameter, IndexOfName returns the position of the first such string.
The following example merges the strings in the memo control into strings contained in the list box. If a string in the memo is of the form Name=Value and the Name is also contained in the list box, its value will be replaced by the list box's value.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int P,DI;
AnsiString S;
for (int i = 0; i <= ListBox1->Items->Count - 1; i++){
S = ListBox1->Items->Strings[i];
P = S.Pos("=");
if (P > 1){
DI = Memo1->Lines->IndexOfName(AnsiString(S.SubString(1, P - 1)));
if (DI > -1)
Memo1->Lines->Strings[DI] = S;
}
}
}
IndexOfObject
Returns the index of the first string in the list associated with a given object.
int __fastcall IndexOfObject(System::TObject* AObject);
Description
Call IndexOfObject to locate the first string in the list associated with the object AObject. Specify the object you want to locate as the value of the AObject parameter. IndexOfObject returns the 0-based index of the string and object. If the object is not associated with any of the strings, IndexOfObject returns -1.
The following code determines if MyObject is the first object in MyStringList.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (ListBox1->Items->IndexOfObject(MyObject) == 0)
ShowMessage("foo");
}
Insert
Inserta una cadena en una posición específica.
virtual void __fastcall Insert(int Index, const System::AnsiString S) = 0;
Memo1->Lines->Insert(2,"Hola");
Description
Descendants of TStrings implement an Insert method to add the string S to the list at the position specified by Index. If Index is 0, the string is inserted at the beginning of the list. If Index is 1, the string is put in the second position of the list, and so on.
All methods that add strings to the list use the Insert method to add the string.
If the string has an associated object, use the InsertObject method instead.
InsertObject
Inserta una cadena en una posición específica de la lista, y asocia esta con un objeto.
void __fastcall InsertObject(int Index, const System::AnsiString S, System::TObject* AObject);
Description
Call InsertObject to insert the string S into the list at the position identified by Index, and associate it with the object AObject. If Index is 0, the string is inserted at the beginning of the list. If Index is 1, the string is put in the second position of the list, and so on.
The following code inserts the components of Form1 into the first position of the Lines list of Memo1.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
for (int i = 0; i < Form1->ComponentCount-1; i++)
Memo1->Lines->InsertObject(0, Form1->Components[i]->Name, this);
}
LoadFromFile
Llena la lista con las líneas de un fichero de texto.
virtual void __fastcall LoadFromFile(const System::AnsiString FileName);
Description
Call LoadFromFile to fill the list of the TStrings object from the file specified by FileName. Each line in the file, as indicated by carriage return or linefeed characters, is appended as a string in the list.
This example uses a memo and a button on a form. When the button is clicked the memo is filled with the contents of the file.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Memo1->Lines->LoadFromFile("Unit1.cpp");
}
LoadFromStream
Llena la lista con las líneas de texto leidas de la consola.
virtual void __fastcall LoadFromStream(TStream* Stream);
Description
Call LoadFromStream to fill the list of the TStrings object from the stream specified by Stream. The text read from the stream is parsed into strings separated by carriage return or linefeed characters. Thus, LoadFromStream reads the value of the Text property.
If the stream is a file stream, LoadFromStream does the same thing as LoadFromFile, except the application must create and destroy the file stream.
This example uses a memo and a button on a form. When the button is clicked the memo is filled with the contents of the file and then saved to a new file.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Memo1->Lines->LoadFromStream(&TFileStream("Unit1.cpp", fmOpenRead));
Memo1->Lines->SaveToStream(&TFileStream("Unit2.cpp", fmOpenWrite));
}
Move
Cambia la posición de una cadena en la lista.
virtual void __fastcall Move(int CurIndex, int NewIndex);
Memo1->Lines->Move(2,4); //Mueve la cadena de la posición 2 a la 4
Description
Use Move to move the string at position CurIndex so that it occupies the position NewIndex. The positions are specified as 0-based indexes. For example, the following line of code moves the string in the first position to the last position.
MyStringsObject->Move(0, MyStringsObject->Count - 1);
If the string has an associated object, the object remains associated with the string in its new position.
This example uses a list box and a button on a form. The list box contains items when the form appears. When the user clicks the button, the fifth item in the list box is moved to the top of the list box:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
ListBox1->Items->Move(4,0);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
for (int i = 0; i < 10; i++)
ListBox1->Items->Append("New String" + AnsiString(i));
}
SaveToFile
Guarda las cadenas en la lista en un fichero.
virtual void __fastcall SaveToFile(const System::AnsiString FileName);
Description
Call SaveToFile to save the strings in the list to the file specified by FileName. Each string in the list is written to a separate line in the file.
This example uses a memo and a button on a form. When the button is clicked the memo is filled with the contents of the file and then saved to a new file.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Memo1->Lines->LoadFromFile("Unit1.cpp");
Memo1->Lines->SaveToFile("Unit2.cpp");
}
SaveToStream
Escribe el valor de la propiedad Text en un objeto Stream.
virtual void __fastcall SaveToStream(TStream* Stream);
Description
Call SaveToStream to save the strings in the list to the stream specified by the Stream parameter. SaveToStream writes the strings delimited by carriage return, line feed pairs. If the stream is a file stream, SaveToStream does the same thing as SaveToFile, except the application must create and destroy the file stream.
This example uses a memo and a button on a form. When the button is clicked the memo is filled with the contents of the file and then saved to a new file.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Memo1->Lines->LoadFromStream(&TFileStream("Unit1.cpp", fmOpenRead));
Memo1->Lines->SaveToStream(&TFileStream("Unit2.cpp", fmOpenWrite));
}
SetText
Inicia la lista con el contenido del texto especificado.
virtual void __fastcall SetText(char * Text);
Description
Call SetText to replace the list with the strings specified by the Text parameter. SetText adds strings one at a time to the list, using the carriage returns or linefeed characters in Text as delimiters indicating when to add a new string.
TStrings
Constructor. Crea un nuevo objeto Tstrings.
__fastcall TStrings(void) : Classes::TPersistent() { }
Description
Do not create instances of TStrings. TStrings methods rely on pure virtual methods that must be overridden in descendant objects.