The following function returns N-th word along with the start position and end position from a string. Here WideString is taken as parameter so that it remains compatible for Unicode string.
Here StringGetNumberOfWords function is used, for details see Get Number of Words within a string in Delphi
function GetWordAndPosition(s: WideString; DelimChar: WideChar; WordNum: integer; var WordStartPos, WordEndPos: integer): WideString;
var
i, WordFound: integer;
begin
if (WordNum StringGetNumberOfWords(s, DelimChar)) then
begin
Result := '';
exit;
end;
WordStartPos := -1;
WordFound := 0;
for i := 1 to Length(s) do
begin
if s[i] DelimChar then
begin
if WordStartPos = -1 then
begin
WordStartPos := i;
Inc(WordFound);
end;
end
else
begin
if WordStartPos -1 then
begin
if WordFound = WordNum then
begin
Result := Copy(s, WordStartPos, i - WordStartPos);
WordEndPos := i - 1;
exit;
end
else
WordStartPos := -1;
end;
end;
end;
Result := Copy(s, WordStartPos, Length(s) - WordStartPos + 1);
WordEndPos := Length(s);
end;
The following function returns N-th word from a string.
function GetWord(s: WideString; DelimChar: WideChar; WordNum: integer): WideString;
var
Dummy1, Dummy2: integer;
begin
Result := GetWordAndPosition(s, DelimChar, WordNum, Dummy1, Dummy2);
end;
- 804 reads