Domanda

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?

È stato utile?

Soluzione

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;

Altri suggerimenti

In Free Pascal, you do not need to be worry about this. You only need to insert the directive {$H+} at the beginning of the source code.

{$H+}

var s: String;

begin
    s := StringOfChar('X', 1000);
    writeln(s);
end.

You can use the AnsiString type.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top