0

I'm trying to find solution, how can I split string like this:

abkgwvc

to array by character? Expected output is:

array[0] = a
array[3] = g
...

any idea?


Solution:

for i := 0 to length(string) do
begin
    array[i] = copy(string, i, 1);
end;
5
  • what language are you using? Commented Nov 4, 2013 at 19:11
  • this page might help you math.uww.edu/~harrisb/courses/cs171/strings.html Commented Nov 4, 2013 at 19:14
  • maybe I can use copy? See my edited question Commented Nov 4, 2013 at 19:16
  • 1
    Your solution is mostly correct, except that your destination array is 0-based and the 3rd parameter to Copy is the number of characters to copy, not the final index. Commented Nov 4, 2013 at 19:18
  • 1
    Strings use a 1-based index in Turbo Pascal. Assuming your array is zero-based, you can actually just do array[i] = string[i+1]; in your loop body and then correct the for to go only up to length(string)-1. Commented Nov 4, 2013 at 19:49

1 Answer 1

7

A string can be accessed as an array of characters directly, so there's no need to use Copy. The example below is based on versions of Delphi/Lazarus that support dynamic arrays, but you can use an old-style fixed length array (Arr: array[..] of Char) the same way; just remove the SetLength call and change the declaration to the right array type.

var
  Str: string;
  Arr: array of Char;
  i: Integer;
  Len: Integer;
begin
  Str := 'abkgwvc';
  Len := Length(Str);
  SetLength(arr, Len);

  // Dynamic arrays are 0-based indexing, while
  // strings are 1 based. We need to subtract 1
  // from the array index.
  for i := 1 to Len do
    Arr[i - 1] := Str[i];  
end;

(Of course, if you're not using dynamic arrays, it's not clear why you'd need a separate array in the first place; you can just access the string char-by-char directly.)

Sign up to request clarification or add additional context in comments.

2 Comments

In TP he is most likely to use shortstrings, which are the default "string" there. No setlength, length assignment is s[0]:=chr(len);
@Marco: The SetLength is being used on a dynamic array, not a string, and I covered older fixed length arrays in the first paragraph. :) Setting the zero byte to a value doesn't set an array's size, only that of a shortstring. Length(s) applies to both ShortString and modern strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.