Re: Delphi: Using only part of a string


[ Delphi Forum -- by DelphiLand ]

Posted by webmaster Guido on January 07, 2004 at 14:52:27:

In Reply to: Re: Using only part of a string posted by WAllison on January 03, 2004 at 21:14:12:

: : I have a problem when using my Delphi TListBox component it is..
: : When i add an item i have made it so that it puts the item number next to the text example.
: : Say it adds 'Hello' in position 20 it will add '20. Hello' but later i need to remove this number how would i go about removing the width of Index + . + ' '??

: try something like:

: Delete(ListBox1.Items[0].Caption,
    1, Pos('. ', ListBox1.Items[0].Caption));

: Delete(string, index, count) - deletes a substring within a string(note the first index is 1 (if u use 0 - it deletes nothing)
: Pos(Substring, string) - returns the index of a substring within a string
----------------------------------------

There are a few errors in this code:

* It should be ListBox1.Items[0] instead of ListBox1.Items[0].Caption;

** You can only pass a string variable to the Pascal procedure Delete(). But ListBox1.Items[0] is not a variable, it's a property of a component, so Delete(ListBox1.Items[0], ...) is invalid.

How it should be done:

1. Put the text of a listbox item in a string variable, say variable S:
      S := ListBox1.Items[0];

2. Delete the first part of this string variable:
      Delete(S, 1, Pos('. ', S);
---------------------------------------------------------------------------------

Example 1: show the selected listbox item in a label, without the "number part":

var
  i: integer;
  S: string;
begin
  i := ListBox1.ItemIndex;      
  if i >= 0 then begin
    S := ListBox1.Items[i];     // S contains '20. Hello'
    Delete(S, 1, Pos('. ', S)); // S contains 'Hello'
    Label1.Caption := S;
  end;  
end;

Example 2: remove the number part from every listbox item:

var
  i: integer;
  S: string;
begin
  for i := 0 to ListBox1.Items.Count - 1 do begin
    S := ListBox1.Items[i];
    Delete(S, 1, Pos('. ', S));
    ListBox1.Items[i] := S;
  end;
end;

Related Articles and Replies:


[ Delphi Forum ]
[ DelphiLand: free Delphi source code, tips, tutorials ]