Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения
KANSoftWare

Парсинг строк

Delphi , Синтаксис , Текст и Строки

Парсинг строк

 
Code:
unit splitfns;
interface
uses Classes, Sysutils;
function GetNextToken(Const S: string; Separator: TSysCharSet; var StartPos: integer): String;
 
{Returns the next token (substring) from string S, starting at index StartPos and ending 1 character
before the next occurrence of Separator (or at the end of S, whichever comes first).}
 
{StartPos returns the starting position for the next token, 1 more than the position in S of
the end of this token}
 
procedure Split(const S: String; Separator: TSysCharSet; MyStringList: TStringList);
 
{Splits a string containing designated separators into tokens and adds them to MyStringList NOTE: MyStringList must be Created before being passed to this procedure and Freed after use}
 
function AddToken (const aToken, S: String; Separator: Char; StringLimit: integer): String;
 
{Used to join 2 strings with a separator character between them and can be used in a Join function}
{The StringLimit parameter prevents the length of the Result String from exceeding a preset maximum}
 
implementation
 
function GetNextToken(Const S: string; Separator: TSysCharSet; var StartPos: integer): String;
var Index: integer;
begin
  Result := '';
{Step over repeated separators}
 While (S[StartPos] in Separator) and (StartPos <= length(S)) do StartPos := StartPos + 1;
 
 if StartPos > length(S) then Exit;
 
{Set Index to StartPos}
 Index := StartPos;
 
{Find the next Separator}
 While not (S[Index] in Separator) and (Index <= length(S))do Index := Index + 1;
 
{Copy the token to the Result}
  Result := Copy(S, StartPos, Index - StartPos);
 
{SetStartPos to next Character after the Separator}
  StartPos := Index + 1;
end;
 
procedure Split(const S: String; Separator: TSysCharSet; MyStringList: TStringList);
var Start: integer;
begin
  Start := 1;
 While Start <= Length(S) do MyStringList.Add(GetNextToken(S, Separator, Start));
end;
 
function AddToken (const aToken, S: String; Separator: Char; StringLimit: integer): String;
begin
 if Length(aToken) + Length(S) < StringLimit then
    begin
      {Add a separator unless the Result string is empty}
      if S = '' then Result := '' else Result := S + Separator;
 
      {Add the token}
      Result := Result + aToken;
    end
 else
 {if the StringLimit would be
  exceeded, raise an exception}
    Raise Exception.Create('Cannot add token');
end;
end.
 
 
пример использования:
 
Code:
...
data:= TStringList.Create;
splited:=TStringList.Create;
data.LoadFromFile(s);
Split(data.Text,[',',' ',#10,#13,';','\"','.','!','-','+','*','/','\',
'(',')','[',']','{','}','<','>','''','"','?','"','#',#0],splited);
for i:= 0 to splited.Count-1 do
begin
    if not words.Find(splited.Strings,adr) then
       words.Add(splited.Strings[i]);
    application.processmessages;[i]//make program to respond to user
       //commands while processing in case of very long string.
end;
...
Автор: Song
Взято из http://forum.sources.ru

Статья Парсинг строк раздела Синтаксис Текст и Строки может быть полезна для разработчиков на Delphi и FreePascal.


Комментарии и вопросы


Ваше мнение или вопрос к статье в виде простого текста (Tag <a href=... Disabled). Все комментарии модерируются, модератор оставляет за собой право удалить непонравившейся ему комментарий.

заголовок

e-mail

Ваше имя

Сообщение

Введите код




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: Текст и Строки ::


реклама



©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru Rambler's Top100

Время компиляции файла: 2024-04-24 22:55:34
2024-04-25 02:28:33/0.0064969062805176/2