Mega Code Archive

 
Categories / Delphi / Functions
 

Simple functions for work with words

Title: Simple functions for work with words Question: How work with words in string ? Answer: In this article means, what separator - symbols #01..#20. This is another version of "Word Count" article by Chris Allsop // get word number N from string S: function word(s: string; n: integer): string; var p:pchar; rv: string; f: boolean; begin p:=pchar(s); f:=false; while (p^ char(0)) do begin if p^ ' ' then begin f:=true; rv:=rv+p^; end else if f then begin if n = 0 then break; dec(n); f:=false; rv:=''; end; inc(p); end; word:=rv; end; // count all words in string S: function words(s: string): integer; var p: pchar; f: boolean; n: integer; begin p:=pchar(s); f:=false; n:=0; while (p^ char(0)) do begin if p^ ' ' then begin if not f then inc(n); f:=true; end else if f then f:=false; inc(p); end; words:=n; end; // get position of N'th word in string S function wordpos(s: string; n:integer):integer; var p: pchar; f: boolean; c: integer; rv: interger; begin p:=pchar(s); f:=false; c:=0; while (p^ char(0)) do begin if p^ ' ' then begin if not f then inc(c); if c = n then break; f:=true; end else if f then f:=false; inc(p); inc(rv); end; wordpos:=rv; end; // cut word number N from string S function wordcut(s: string; n: integer): string; begin wordcut:=copy(s,wordpos(s,n+1),length(s)-wordpos(s,n+1)+1); end;