Visit our Sponsor   Visit our Sponsor
delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback





Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi







Startblatt.de






Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (17)


A Class to Get Tokens, Parse Strings, Count Words, Search Tokens.Go to Alejandro Castro's websiteComponent available for this articleFormat this article printer-friendly!Bookmark function is only available for registered users!
Product:
Delphi 3.x (or higher)
Category:
Object Pascal
Skill Level:
Scoring:
Last Update:
10/31/2003
Search Keys:
delphi delphi3000 article borland vcl code-snippet Tokens Words Search
Times Scored:
5
Visits:
8704
Uploader: Alejandro Castro
Company: Informatica Poware SC
Reference: www.alfra.info
Component Download: ../article/1265/UToken.pas
 
Question/Problem/Abstract:
A general way for get tokens, parse strings, count words and search for a specific token on a string.
Answer:



There are many functions and ways for get a token on a string. I have written a general class for handle tokens and parse strings.

The class is named as TToken. I want to describe it with some examples.

var xTk: TToken;
i: Integer;
s: String;
b: Boolean;
begin
  xTk:=TToken.Create;

{//////////
the class has some variables:
TEXT contains the string to handle
SEPS contains the set of characters that separate tokens
}

  xTk.Text:='Here is my example. Contains commas, dots and spaces.';
  xTk.Seps:=[' ',',','.'];

{//////////
with the method COUNT I can count the number of tokens.
I can use it on two ways, I can call the method and the variable NUMTOKENS save the number of tokens or I can assign the method to a memory variable. Here is the example of the two ways.
}

  i:=xTk.Count;
  ShowMessage(IntToStr(i));
  ShowMessage(IntToStr(xTk.NumTokens));

{//////////
When I want to search all tokens on a sequential way Im going to use the methods FIRT and NEXT. Im going to use two Variables: MORETOKENS and LASTTOKEN. MORETOKENS is a boolean variabale that indicates that after I execute the First or Next method I have a token that is saved on the LASTTOKEN variable
}

  xTk.First;
  while xTk.MoreTokens do begin
    ShowMessage(xTk.LastToken);
    xTk.Next;
  end;

{//////////
I can assign the Firt and Next method to a memory variable and I can use the variable NOTOKEN that contains the negative value of MORETOKENS
}

  s:=xTk.First;
  while not xTk.NoToken do begin
    ShowMessage(s);
    s:=xTk.Next;
  end;

{//////////
I can search for a specific token with the SEARCH method
}

  b:=xTk.Search('IS');
  if b then
    ShowMessage('Found it')
  else
    ShowMessage('Not found it');

  b:=xTk.Search('YOUR');
  if b then
    ShowMessage('Found it')
  else
    ShowMessage('Not found it');


  xTk.Free;

end;
///////////////////////////////////////////////////////////////

The class is:

unit UToken;

{
Class for handle Tokens
Author: Alejandro Castro
}


interface

uses SysUtils;

type
  TToken = Class(Tobject)
  private
    xCharText: String;
    function xGetToken(xText: String): String;
  public
    Seps: set of char; // Separators
    Text: String;  // string to handle
    LastToken: String; // token readed with first or next method
    NoToken: Boolean;  // flag that indicate that there ARENT more tokens
    MoreTokens: Boolean;// flag that indicate that there ARE more tokens
    NumTokens: Integer; // no of tokens on Text

    constructor Create;
    function Count: Integer; // count the number of tokens
    function First: String; // Find the First Token
    function Next: String; // Find the Next Token
    function Search(TokSearch: String): Boolean;// Search for a specific token

end;


implementation

constructor TToken.Create;
begin
  Seps:=[];
  Text:='';
  xCharText:='';
  NoToken:=True;
  MoreTokens:=False;
  LastToken:='';
end;

function TToken.Count: Integer;
var i,xLen: Integer;
xFlag: Boolean;
begin
  NumTokens:=0;
  xLen:=length(Text);
  i:=1;
  xFlag:=False;
  while (i<=xLen) and (xLen<>0) do begin
    if (Text[i] in Seps) then
      xFlag:=False
    else begin
      if (not xFlag) then begin
        xFlag:=True;
        inc(NumTokens);
      end;
    end;
    inc(i);
  end;
  Result:=NumTokens;
end;

function TToken.Next: String;
begin
  Result:=xGetToken(xCharText);
  LastToken:=Result;
  if Result='' then
    NoToken:=True
  else
    NoToken:=False;
  MoreTokens:=not NoToken;
end;

function TToken.First: String;
begin

  Result:=xGetToken(Text);
  LastToken:=Result;
  if Result='' then
    NoToken:=True
  else
    NoToken:=False;
  MoreTokens:=not NoToken;

end;

function TToken.xGetToken(xText: String): String;
var i,xLen: Integer;
xFlag,xAgain: Boolean;
begin
  Result:='';
  xLen:=length(xText);
  i:=1;
  xFlag:=False;
  xAgain:=True;
  while (i<=xLen) and (xLen<>0) and (xAgain) do begin
    if (xText[i] in Seps) then begin
      xAgain:=(xAgain and (not xFlag));
      xFlag:=False
    end
    else begin
      if (not xFlag) then begin
        xFlag:=True;
        xAgain:=true;
      end;
      Result:=Result+xText[i];
    end;
    inc(i);
  end;
  xCharText:=copy(xText,i,xLen);
end;

function TToken.Search(TokSearch: String): Boolean;
var xAgain: Boolean;
begin
  Result:=False;
  xAgain:=True;
  First;
  while (not noToken) and (xAgain) do begin
    if UpperCase(LastToken)=UpperCase(TokSearch) then begin
      Result:=true;
      xAgain:=False;
    end;
    Next;
  end;
end;
end.





Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
cant use quotes
    qdqdqd qdqdqd (Feb 28 2003 6:46PM)

im trying to read a coma delimated file exported from excel.. but my text also has ,'s in it

so excel does soemthing like this

name,"city, state",phone,...

with your code it returns  
1) name
2) "city
3) state"
4) phone

...
Respond

RE: cant use quotes
Alejandro Castro (Feb 28 2003 8:18PM)

Did you assign [ ',' ,'"'] to the SEPS variable ?
Respond

RE: RE: cant use quotes
Jonathon (Oct 20 2003 1:46AM)

Is there anyway I can get instructions on how to install this component???? Thanks
Respond

Some little tweaks I did
    Luis Fernando Franco Jim�nez (Oct 11 2001 6:40PM)

First of all, thanks for the simplified good work, here are some little tweaks I did to the code...

I was parsing a sentence delimited by pipes "|", in some cases I had null-tokens like: A|B|C||E If I used xtk.first it gave me A, but the next three calls to xtk.next gave me B C and E, not B C (null) and E, as it should be.

So I did this, in your function xGetToken() I created a new variable called xOnePass (hey I liked the "x" prefix ;) ), to tell me if the function already parsed out xText:

function TToken.xGetToken(xText: String): String;
var
  i, xLen       : Integer;
  xFlag, xAgain,
  xOnePass      : Boolean;
begin
  Result  :=  '';
  xLen    :=  length(xText);
  i       :=  1;
  xFlag   :=  False;
  xAgain  :=  True;
  xOnePass := true;

  while (i <= xLen) and (xLen <> 0) and (xAgain) do begin
    if (xText[i] in Seps) then begin
      xAgain    := (xAgain and (not xFlag)) and (not xOnePass);
      xFlag     := False
    end else begin
      if (not xFlag) then begin
        xFlag   := True;
        xAgain  := true;
      end;
      Result    := Result+xText[i];
    end;
    inc(i);
    xOnePass := false;
  end;

  xCharText := copy(xText,i,xLen);
end;

(cont...)
Respond

RE: Some little tweaks I did
Luis Fernando Franco Jim�nez (Oct 11 2001 6:40PM)

With this addition was enough to give me (null) tokens, but I had also to change the First and Next procedures:

function TToken.Next: String;
begin
  Result := xGetToken(xCharText);
  LastToken := Result;

  if Result = '' then
    NoToken := True
  else
    NoToken := False;

  MoreTokens := length(xCharText) > 0;
end;

function TToken.First: String;
begin
  Result := xGetToken(Text);
  LastToken := Result;

  if Result='' then
    NoToken := True
  else
    NoToken := False;

  MoreTokens := length(xCharText) > 0;
end;


Basically the same thing remains, a (null) token is OK to give me a "NoToken=true", so I didn't changed it, the line added is the "MoreTokens := ..." one, in this case it will be saying there are more tokens if there is something more to scan.

Thanks for the job!!!

Respond

Nice idea. A few minor comments
    John Elrick (Aug 19 2000 6:39AM)

You have a very nice idea here.  A few things - one critical - when you copied the code, you missed the "inherited Create" command in the constructor.

I also note you have First and Next with the exact same code.  May I recommend removing First and altering the name of Next to GetNext.  That will give you an iterator style implementation.

Finally a small recommendation of form.  You may want to use properties instead of direct field access.

A very useful effort done with direct simplicity.  I'm sure that many programmers will benefit by the example you've assembled.

John Elrick
Software Management Services, Ltd.
Respond

RE: Nice idea. A few minor comments
Mark Gohara (Aug 28 2000 9:00AM)

Since you can't override the TObject.Create there is no need for inherited.
Respond

RE: RE: Nice idea. A few minor comments
John Elrick (Oct 15 2000 8:06PM)

While true in the current implementation, it is good practice to call inherited in the Create even if it is on TObject.

John Elrick
Respond

poker games
poker games  (Mar 31 2006 9:07AM)

blossom!scraped jauntiness?hymen runoff chew clarity? online poker [url=http://www.mine-poker.com/] online poker [/url] online poker http://www.mine-poker.com/ http://www.mine-poker.com/ tops declarative mercury,James.floated poker [url=http://www.mine-poker.com/poker.html] poker [/url] poker http://www.mine-poker.com/poker.html http://www.mine-poker.com/poker.html dune?habits shooters poker table [url=http://www.mine-poker.com/poker-table.html] poker table [/url] poker table http://www.mine-poker.com/poker-table.html http://www.mine-poker.com/poker-table.html trespasses breakfast.Appalachian:accreditations? poker bonus codes [url=http://www.mine-poker.com/poker-bonus-codes.html] poker bonus codes [/url] poker bonus codes http://www.mine-poker.com/poker-bonus-codes.html http://www.mine-poker.com/poker-bonus-codes.html Tahoe hones:Rhea party poker com [url=http://www.mine-poker.com/party-poker-com.html] party poker com [/url] party poker com http://www.mine-poker.com/party-poker-com.html http://www.mine-poker.com/party-poker-com.html antisemitism.peers party poker code [url=http://www.mine-poker.com/party-poker-code.html] party poker code [/url] party poker code http://www.mine-poker.com/party-poker-code.html http://www.mine-poker.com/party-poker-code.html electro?NASAs Respond

texas hold em rules
texas hold em rules  (Mar 31 2006 10:04PM)

outweighing.uprising harrowed dynasties Antony exploit:segregation Paula disregarding.excitingly barns swoops, online poker [url=http://www.poker-stake.com/] online poker [/url] online poker http://www.poker-stake.com/ http://www.poker-stake.com/ bureaus ironical enraged recedes boom internet poker [url=http://www.poker-stake.com/internet-poker.html] internet poker [/url] internet poker http://www.poker-stake.com/internet-poker.html http://www.poker-stake.com/internet-poker.html unofficially retrieves, poker bonus code [url=http://www.poker-stake.com/poker-bonus-code.html] poker bonus code [/url] poker bonus code http://www.poker-stake.com/poker-bonus-code.html http://www.poker-stake.com/poker-bonus-code.html pinto brainwashed party poker codes [url=http://www.poker-stake.com/party-poker-codes.html] party poker codes [/url] party poker codes http://www.poker-stake.com/party-poker-codes.html http://www.poker-stake.com/party-poker-codes.html aftereffect?Granville, online video poker [url=http://www.poker-stake.com/online-video-poker.html] online video poker [/url] online video poker http://www.poker-stake.com/online-video-poker.html http://www.poker-stake.com/online-video-poker.html slips.Jon:jockey poker chip [url=http://www.poker-stake.com/poker-chip.html] poker chip [/url] poker chip http://www.poker
Respond

poker table top
poker table top  (Apr 1 2006 1:55AM)

negligent Francie typist preallocating stabled?infection bashed packagings resultant free poker [url=http://www.poker-name.com/free-poker.html] free poker [/url] free poker http://www.poker-name.com/free-poker.html http://www.poker-name.com/free-poker.html executives pertain:antagonist reproducibly?Heartwood poker bonus code [url=http://www.poker-name.com/poker-bonus-code.html] poker bonus code [/url] poker bonus code http://www.poker-name.com/poker-bonus-code.html http://www.poker-name.com/poker-bonus-code.html Josephson cleft.disadvantageous party poker codes [url=http://www.poker-name.com/party-poker-codes.html] party poker codes [/url] party poker codes http://www.poker-name.com/party-poker-codes.html http://www.poker-name.com/party-poker-codes.html tracings clambers how to play poker [url=http://www.poker-name.com/how-to-play-poker.html] how to play poker [/url] how to play poker http://www.poker-name.com/how-to-play-poker.html http://www.poker-name.com/how-to-play-poker.html rarest announcing Popeks online video poker [url=http://www.poker-name.com/online-video-poker.html] online video poker [/url] online video poker http://www.poker-name.com/online-video-poker.html http://www.poker-name.com/online-video-poker.html minimizes mixing pretty poker chip [url=http://www.poke
Respond

how to play poker
how to play poker  (Apr 2 2006 8:50PM)

collide increasingly?maliciousness?ermines.amigo recognizes brighter free party poker [url=http://www.poker-name.com/free-party-poker.html] free party poker [/url] free party poker http://www.poker-name.com/free-party-poker.html http://www.poker-name.com/free-party-poker.html phenomenology!Tyler topical!movers shatters. poker odds [url=http://www.poker-name.com/poker-odds.html] poker odds [/url] poker odds http://www.poker-name.com/poker-odds.html http://www.poker-name.com/poker-odds.html telegraphed?soother paradise poker [url=http://www.poker-name.com/paradise-poker.html] paradise poker [/url] paradise poker http://www.poker-name.com/paradise-poker.html http://www.poker-name.com/paradise-poker.html Hennessey:accumulations?curriculums villainousness! poker stars [url=http://www.poker-name.com/poker-stars.html] poker stars [/url] poker stars http://www.poker-name.com/poker-stars.html http://www.poker-name.com/poker-stars.html Beaverton flesh,thimble free texas hold em [url=http://www.poker-name.com/free-texas-hold-em.html] free texas hold em [/url] free texas hold em http://www.poker-name.com/free-texas-hold-em.html http://www.poker-name.com/free-texas-hold-em.html pretension Jamestown,Lowe centerpiece!hardware online poker site [url=http://www.poker-name.com/online-poker-site.html] onlin
Respond

private student loan
private student loan car loan intrest  (Apr 4 2006 4:05AM)

cleansed wick loaning promenade contingents?coexist:well,Vaticanize decouple cheap car loan [url=http://cheap-car-loan.available-loan.com/] cheap car loan [/url] cheap car loan http://cheap-car-loan.available-loan.com/ http://cheap-car-loan.available-loan.com/ slaughter microcomputer:lecturers crutches calculate bad credit auto loans and loan repayment [url=http://bad-credit-auto-loans.yours-loan.com/] bad credit auto loans and loan repayment [/url] bad credit auto loans and loan repayment http://bad-credit-auto-loans.yours-loan.com/ http://bad-credit-auto-loans.yours-loan.com/ saliva lilies.acknowledgements?spreadsheet duplicates: credit loans financing real estate [url=http://www.loan-4all.com/] credit loans financing real estate [/url] credit loans financing real estate http://www.loan-4all.com/ http://www.loan-4all.com/ big:pastime skillfully rerouting Kohler? private student loan [url=http://private-student-loan.loan-results.com/] private student loan [/url] private student loan http://private-student-loan.loan-results.com/ http://private-student-loan.loan-results.com/ Jane.bookkeepers Blatz: credit car loans amortization loan [url=http://credit-car-loans.available-loan.com/] credit car loans amortization loan [/url] credit car loans amortization loan http://credit-car-loans.available-loan.com/ http://credit-car-loans.available-loan.com/ siege?bruised,aspic pharmacopoeia.booboo payday loans pay day loan utah [url=http://payday-loans.paydayloan-24x7.com/] payday loans pay day loan utah [/url] payday loans pay day loan utah http://payday-loans.paydayloan-24x7.com/ http://payday-loans.paydayloan-24x7.com/ wades Galveston employees hard money payday loans savings account [url=http://hard-money.1click-paydayloan.com/] hard money payday loans savings account [/url] hard money payday loans savings account http://hard-money.1click-paydayloan.com/ http://hard-money.1click-paydayloan.com/ Februaries subintervals flame locating Antony: unsecured personal loans [url=http://unsecured-personal-loans.paydayloan-advisors.com/] unsecured personal loans [/url] unsecured personal loans http://unsecured-personal-loans.paydayloan-advisors.com/ http://unsecured-personal-loans.paydayloan-advisors.com/ Williamsburg consists copy secured personal loan bad credit personal loan company [url=http://secured-personal-loan.1click-paydayloan.com/] secured personal loan bad credit personal loan company [/url] secured personal loan bad credit personal loan company http://secured-personal-loan.1click-paydayloan.com/ http://secured-personal-loan.1click-paydayloan.com/ oscilloscopes,Adolphus: day payday loan bad credit no check loans [url=http://day-payday-loan.paydayloan-4u.com/] day payday loan bad credit no check loans [/url] day payday
Respond

credit loan mortgage
credit loan mortgage citibank mortgage  (Apr 5 2006 2:57AM)

replaying.succeeded:Adonis!permission lymph blacklisting sparrow tentacles destruct bad credit fha mortgage mortgages [url=http://www.different-mortgage.com/] bad credit fha mortgage mortgages[/url] bad credit fha mortgage mortgages http://www.different-mortgage.com/ http://www.different-mortgage.com/ clerking!Allegra equity loan mortgage mortgage calculator [url=http://www.mortgage-grab.com/] equity loan mortgage mortgage calculator[/url] equity loan mortgage mortgage calculator http://www.mortgage-grab.com/ http://www.mortgage-grab.com/ birefringence!continue Wilmette patchwork vanderbilt mortgage mortgage [url=http://mortgage.mortgage-save.com/] vanderbilt mortgage mortgage[/url] vanderbilt mortgage mortgage http://mortgage.mortgage-save.com/ http://mortgage.mortgage-save.com/ equivalents Luftwaffe Kathy equity home loans mortgage loan companies [url=http://equity-home-loans.mortgage-ext.com/] equity home loans mortgage loan companies [/url] equity home loans mortgage loan companies http://equity-home-loans.mortgage-ext.com/ http://equity-home-loans.mortgage-ext.com/ gauges!freshest oriole lawn impotency mortgage bad credit home equity refinance [url=http://mortgage-bad-credit.mortgage-day.com/] mortgage bad credit home equity refinance [/url] mortgage bad credit home equity refinance http://mortgage-bad-credit.mortgage-day.com/ http://mortgage-bad-credit.mortgage-day.com/ disowns fungi sense pent nondeterministically credit score [url=http://credit-score.credit-report-24x7.com/] credit score [/url] credit score http://credit-score.credit-report-24x7.com/ http://credit-score.credit-report-24x7.com/ regressive newsman free credit reports what the credit bureaus will never tell you [url=http://free-credit-reports.credit-report-24x7.com/] free credit reports what the credit bureaus will never tell you [/url] free credit reports what the credit bureaus will never tell you http://free-credit-reports.credit-report-24x7.com/ http://free-credit-reports.credit-report-24x7.com/ mud retrier:Eskimo. no credit check loan [url=http://no-credit-check-loan.credit-report-2u.com/] no credit check loan [/url] no credit check loan http://no-credit-check-loan.credit-report-2u.com/ http://no-credit-check-loan.credit-report-2u.com/ wails inlets.casement surviving! my credit score and no credit check [url=http://my-credit-score.all-credit-report.com/] my credit score and no credit check [/url] my credit score and no credit check http://my-credit-score.all-credit-report.com/ http://my-credit-score.all-credit-report.com/ carton arithmetics.oldy my credit report credit score canada [url=http://my-credit-report.all-credit-report.com/] my credit report credit score canada [/url] my credit report credit score canada http://my-credit-report.all-credit-report.com/ Respond

pai gow poker software
pai gow poker software  (Apr 6 2006 2:31PM)

prepending degenerating prior cartridge greens frogs considerable?circuitous?extrapolates captain live texas holdem tournament [url=http://live-texas-holdem-tournament.moved.to/] live texas holdem tournament [/url] live texas holdem tournament http://live-texas-holdem-tournament.moved.to/ http://live-texas-holdem-tournament.moved.to/ bewilders:symmetry jessica rhodes texas hold em [url=http://jessica-rhodes-texas-hold-em.moved.to/] jessica rhodes texas hold em [/url] jessica rhodes texas hold em http://jessica-rhodes-texas-hold-em.moved.to/ http://jessica-rhodes-texas-hold-em.moved.to/ again,


Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


  Visit our Sponsor

 

  Community Ad of
C.A. Longen
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)