A ShortString
is 0 to 255 characters long. While the length of a ShortString can
change dynamically, its memory is a statically allocated 256 bytes; the first
byte stores the length of the string, and the remaining 255 bytes are available
for characters. If S is a ShortString variable, Ord(S[0]), like
Length(S), returns the length of S; assigning a value to S[0], like calling SetLength,
changes the length of S. ShortString uses 8-bit ANSI characters and is
maintained for backward compatibility only.
Object
Pascal supports short-string types in effect, subtypes of ShortString whose
maximum length is anywhere from 0 to 255 characters. These are denoted by a
bracketed numeral appended to the reserved word string. For example,
var
MyString: string[100];
creates a variable called MyString
whose maximum length is 100 characters. This is equivalent to the declarations
type
CString = string[100];
var
MyString: CString;
Variables
declared in this way allocate only as much memory as the type requires, that
is, the specified maximum length plus one byte. In our example, MyString
uses 101 bytes, as compared to 256 bytes for a variable of the predefined ShortString
type.
When you
assign a value to a short-string variable, the string is truncated if it
exceeds the maximum length for the type.
The standard functions High and Low operate on short-string type identifiers and variables. High returns the maximum length of the short-string type, while Low returns zero.
ShortString类型串的长度在0到255之间。ShortString串的长度可以动态改变,其占用的内存是静态的,总是256字节;第一个字节存储串的长度,其余255个字节存储串中的字符。如果S是一个ShortString类型的变量,那么,和 Length(S) 一样,Ord(S[0]) 返回串的长度;对S[0] 赋值则相当于调用了SetLength,可以改变串的长度。ShortString使用8位ANIS字符并且仅用于向后兼容。
Object
Pascal还支持其他最大长度在0到255之间的短串。可以通过在保留字string后边附加方括号括起来的数字类表示。例如:
var
MyString: string[100];
创建了一个叫做MyString的变量,其对大长度为100个字符。上面的声明等价于:
type
CString = string[100];
var
MyString: CString;
这中方式声明的变量仅为其分配其类型声明必需的内存,也就是指定最大长度加1个字节。这里声明的MyString变量使用101个字节的内存,这与预定义的ShortString类型使用256个字节情形相似。
向短串变量赋值时,如果值的长度超过了该变量的最大长度,那么串将被截断成该变量的最大长度。
标准函数High和Low可以作用于短串类型标识符和短串变量。High返回短串类型的最大长度,Low返回0。
编者注
下面的代码说明了短串的一些基本特点:
var
S1: string[1];//占用2字节内存
S2: string[0];//占用1字节内存
S3: string[5];//占用6字节内存
begin
S1 := 'OK'; //执行后S1的值是 'O'
S2 := 'HELLO'; //执行后S2的值是 '' ,并且总是该空串
S3 := 'Object Pascal'; //执行后S3的值是 'Objec'
...
end;