Q
Q
quintbrut2020-01-22 06:45:32
Pascal
quintbrut, 2020-01-22 06:45:32

How to split a string into an array by space?

Let's say there is a string:
Arbitrary string
It should be like this:
['Arbitrary', 'string']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
HemulGM, 2020-01-22
@quintbrut

You loop through the string, if there is a space, then from the beginning to the space you put it in an array.
I recommend that you first count the spaces in one cycle. Set array size = number of spaces + 1.
Next, fill the array.
You need a variable that will remember the last position
of LastPos
AND a variable of the last element
LastIndex
Well, here it is:

SetLength(a, SpaceCount + 1);
LastPos := 1;
LastIndex := 0;
for i := 1 to Length(Str) do
  if Str[i] = ' ' then
  begin
    a[LastIndex] := Copy(Str, LastPos, (i - LastPos)); //-- тут возможно +-1
    Inc(LastIndex);
    LastPos := i;
  end;

This is if for pure Pascal, and if for Delphi, then it is better to use TStringList and its DelemitedText method

Z
zed, 2020-01-22
@zedxxx

Use the Split property :

uses 
  ...
  SysUtils;
     
var
  I: Integer;
  VStr: string;
  VArr: TStringArray;
begin
  VStr := 'Произвольная строка';
  VArr := VStr.Split(' ');

  for I := 0 to Length(VArr) - 1 do begin
    WriteLn(VArr[I]);
  end;
end;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question