Как вытащить N-е слово из строки?
Приведен пример вытаскивания N-го слова в строке на примере переменной окружения PATH.
Type
CharSet = Set of Char ;
function WordCount(S : string; WordDelims : CharSet) : Byte;
{-Given a set of word delimiters, return number of words in S}
var
I, Count : Byte;
SLen : Byte absolute S;
begin
Count := 0;
I := 1;
while I <= SLen do begin
{skip over delimiters}
while (I <= SLen) and (S[I] in WordDelims) do
Inc(I);
{if we're not beyond end of S, we're at the start of a word}
if I <= SLen then
Inc(Count);
{find the end of the current word}
while (I <= SLen) and not(S[I] in WordDelims) do
Inc(I);
end;
WordCount := Count;
end;
function ExtractWord(N : Byte; S : string; WordDelims : CharSet) : string;
{-Given a set of word delimiters, return the N'th word in S}
var
I, Count, Len : Byte;
SLen : Byte absolute S;
begin
Count := 0;
I := 1;
Len := 0;
ExtractWord[0] := #0;
while (I <= SLen) and (Count <> N) do begin
{skip over delimiters}
while (I <= SLen) and (S[I] in WordDelims) do
Inc(I);
{if we're not beyond end of S, we're at the start of a word}
if I <= SLen then
Inc(Count);
{find the end of the current word}
while (I <= SLen) and not(S[I] in WordDelims) do begin
{if this is the N'th word, add the I'th character to Tmp}
if Count = N then begin
Inc(Len);
ExtractWord[0] := Char(Len);
ExtractWord[Len] := S[I];
end;
Inc(I);
end;
end;
end;
>(* example *)
Uses
Dos;
Var
S : String ;
i : Byte ;
begin
S := GetEnv('PATH') ;
WriteLn('Path`s directories :') ;
for i := 1 to WordCount(S,[';']) do
WriteLn(ExtractWord(i,S,[';'])) ;
end.