Long strings in pascal
freepascal, pascal
Solution
Old-style (Turbo Pascal, or Delphi 1) strings, now known as `ShortString`, are limited to 255 characters (byte 0 was reserved for the string length). This appears to still be the default in FreePascal (according to @MarcovandeVoort's comment below). Keep reading, though, until you get to the discussion and code sample for `AnsiString` below. :-)
Currently, most other dialects of Pascal I'm aware of default to either `AnsiString` (long strings of single byte characters) or `UnicodeString` (long strings of multi-byte characters). Neither of those are limited to 255 characters.
The current versions of Delphi defaults to `UnicodeString` as the default type, so declaring a `string` variable is in fact a long `UnicodeString`. There is no practical upper limit to the string length:
var
Test: string; // Declare a new Unicode string
begin
SetLength(Test, 100000); // Initialize it to hold 100000 characters
Test := StringOfChar('X', 100000); // Fill it with 100000 'X' characters
end;
If you want to force single-byte characters (but not be limited to 255 character strings), use `AnsiString` (which can set as the default `string` type in FreePascal if you use the `{$H+}` compiler directive - thanks @MarcovandeVoort):
var
Test: AnsiString; // Declare a new Ansistring
begin
SetLength(Test, 100000); // Initialize it to hold 100000 characters
Test := StringOfChar('X', 100000); // Fill it with 100000 'X' characters
end;
Finally, if you do for some unknown reason want to use the old style `ShortString` that is restricted to 255 characters, declare it as such, either using `ShortString` or the old style `String[Size]` declaration:
var
Test: ShortString; // Declare a new short string of 255 characters
ShortTest: String[100]; // Also a ShortString of 100 characters
begin
// This line won't compile, because it's too large for Test
Test := StringOfChar('X', 100000); // Fill it with 100000 'X' characters
end;
Problem
I want to be able to use a string that is quite long (not longer then 100000 signs). As far as I know a typical string variable can cotain only up to 256 chars. Is there a way to store such a long string?