[fpc-pascal] splitting string into array

Andrea Mauri andrea.mauri at unimib.it
Tue Jul 10 18:19:57 CEST 2007


occurs is:

function Occurs(const str, separator: string): integer;
var
  i, nSep: integer;
begin
  nSep:= 0;
  for i:= 1 to Length(str) do
    if str[i] = separator then Inc(nSep);
  Result:= nSep;
end;

Andrea Mauri ha scritto:
> I used this, check it.
>
> // Returns an array with the parts of "str" separated by "separator"
> function Split(const str: string; const separator: string): array of 
> string;
> var
>  i, n: integer;
>  strline, strfield: string;
> begin
>  n:= Occurs(str, separator);
>  SetLength(Result, n + 1);
>  i := 0;
>  strline:= str;
>  repeat
>    if Pos(separator, strline) > 0 then
>    begin
>      strfield:= Copy(strline, 1, Pos(separator, strline) - 1);
>      strline:= Copy(strline, Pos(separator, strline) + 1, 
> Length(strline) - pos(separator,strline));
>    end
>    else
>    begin
>      strfield:= strline;
>      strline:= '';
>    end;
>    Result[i]:= strfield;
>    Inc(i);
>  until strline= '';
>  if Result[High(Result)] = '' then SetLength(Result, Length(Result) -1);
> end;     
> andrea
>
> Wolfram Kläger ha scritto:
>> Here is a Delphi implementation of the common PHP function 'explode'.
>>
>> http://www.michael-puff.de/Developer/Delphi/Code-Snippets/Explode.html
>>
>> Your example then becomes to
>> ..
>> A := Explode('-', 'ab-cd-ef');
>> writeln(A[1]); // expect 'cd'
>> ..
>>
>> The inverse is accomplished by using PHP like 'implode', which glues 
>> all splitted parts back to a single string.
>>
>> Wolfram
>>
>>
>>
>>  
>>> -----Ursprüngliche Nachricht-----
>>> Von: FPC-Pascal users discussions <fpc-pascal at lists.freepascal.org>
>>> Gesendet: 10.07.07 13:04:31
>>> An: FPC-Pascal users discussions <fpc-pascal at lists.freepascal.org>
>>> Betreff: [fpc-pascal] splitting string into array
>>>     
>>
>>
>>  
>>> Hi,
>>>
>>> is there any function in the libraries of fpc for splitting a string
>>> into an array naming the separator?
>>>
>>> In awk for eample if you do this:
>>>
>>>     split("ab-cd-ef", x, "-")
>>>     print x[2]
>>>
>>> it would split up the first string using "-" as separator and print
>>>
>>>     cd
>>>
>>> to the output. That's what I'm searching for.
>>> In pascal. ;)
>>>
>>> TIA,
>>> Marc
>>>
>>>
>>> _______________________________________________
>>> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
>>> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>>>
>>>     
>> _______________________________________________
>> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
>> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>>
>>   
>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>




More information about the fpc-pascal mailing list