Free Pascal soporta varios tipos de character and string. Estos van desde simples caracteres ANSI a cadenas UNICODE y además incluye los tipos puntero. Las diferencias también se aplican a las codificaciones y reference counting.
AnsiChar
editUn tipo de variable AnsiChar, también referenciado como char, es exactamente de 1 byte de tamaño, y contiene un carácter ANSI.
| a |
Referencia
editWideChar
editUna variable de tipo WideChar, también referenciada como UnicodeChar, es exactamente de 2 bytes de tamaño, y contieen un (parte de) Unicode character in UTF-16 encoding. Nota: es imposible codificar todos los puntos codificables Unicode con 2 bytes. Therefore, se pueden necesitar 2 WideChars para codificar un solo code point.
| a |
Referencias
edit- Documentación FPC sobre WideChar
- Información sobre UTF-16 en la Wikipedia
- RTL Documentación UnicodeChar
Martriz de caracteres (Array of Char)
editLas implementaciones tempranas de Pascal existentes antes de 1978 no soportaba el tipo string (con la excepción de las constantes cadena). La única posibilidad de almacenar cadenas en variables era utilizar matrices de caracteres (array of char). Esta aproximación tiene bastantes desventajas y se desaconseja su uso. Se soporta todavía para asegurar la compatibilidad con código antiguo.
Matriz estática de Char
edittype
TOldString4 = array[0..3] of char;
var
aOldString4: TOldString4;
begin
aOldString4[0] := 'a';
aOldString4[1] := 'b';
aOldString4[2] := 'c';
aOldString4[3] := 'd';
end;
La matriz estática de caracteres tiene ahora el siguiente contenido:
| a | b | c | d |
![]()
Nota: Los chars no asignados pueden tener cualquier contenido, dependiendo de lo que exista en ese área de memoria cuando se haga disponible la matriz.
Matriz dinámica de Char
editvar
aOldString: Array of Char;
begin
SetLength(aOldString, 5);
aOldString[0] := 'a';
aOldString[1] := 'b';
aOldString[2] := 'c';
aOldString[3] := 'd';
end;
La matriz dinámica de caracteres tiene ahora el siguiente contenido:
| a | b | c | d | #0 |
![]()
Nota: los Chars no asignados en matrices dinámicas tienen como contenido #0, causando que todas las posiciones vacias de las matrices dinámicas sean inicializados al principio con 0 (o #0, o nil, o ...)
PChar
editUna variable de tipo PChar es básicamente un puntero a un tipo Char, pero que permite operaciones adicionales. Pchars se pueden utilizar para acceder al estilo C null-terminated strings, e.g. en interacciones con ciertas librerías del Sistema Operativo o en software de terceros.
| a | b | c | #0 |
| ^ |
Referencia
editPWideChar
editA variable of type PWideChar is a pointer to a WideChar variable.
| a | b | c | #0 | #0 | |||
| ^ |
Texto de encabezado
editReferencia
editString
editEl tipo String puede hacer referencia a ShortString o AnsiString, dependiendo del {$H} interruptor. Si el interruptor está en off ({$H-}) entonces cualquier declaración de string se definirá como ShortString. El tamaño será de 255 caracteres, si no está especificado de otro modo. Si el interruptor está en on ({$H+}) un string sin especificación de tamaño será definido como un AnsiString, caso contrario (especificando el tamaño) será definido como ShortString con el tamaño especificado. En mode delphiunicode String es UnicodeString.
Reference
editShortString
editShort strings tienen una longitud máxima de 255 caracteres con los codepage implícitos CP_ACP
La longitud o tamaño se almacena en el caracter de índice 0 (cero).
| #3 | a | b | c |
Reference
editAnsiString
editAnsistrings son cadenas que no tienen límite de longitud. Son reference counted y se garantiza que son terminadas con null. Internamente, una variable de tipo AnsiString se trata como un puntero: el actual contenido de la cadena se almacena en montón (heap), se ubica tanta cantidad de memoria como sea necesaria.
| a | b | c | #0 | ||||||||
| RefCount | Length | ||||||||||
Referencia
editUnicodeString
editAl igual que AnsiStrings, UnicodeStrings son reference counted, matrices terminadas con null, pero son implementadas como matrices de WideChars en lugar de Chars regulares.
![]()
Nota: La nomenclatura UnicodeString es un poco ambigua debido a su uso en Delphi bajo Windows, donde los sistemas operativos utilizan cofificación UTF16; no es el único tipo que puede albergar cadenas de datos Unicode (ver también UTF8String)...
| a | b | c | #0 | #0 | |||||||||||
| RefCount | Length | ||||||||||||||
Referencia
editUTF8String
editEn la versión FPC 2.6.5 e inferiores el tipo UTF8String era un alias del tipo AnsiString. En FPC 2.7.1 y posteriores se define como:
UTF8String = type AnsiString(CP_UTF8);
Esto significa que contienen cadenas codificadas como UTF-8 (i.e. datos unicode) oscilando entre 1..4 bytes por carácter.
Ten en cuenta que un String puede también contener caracteres codificados enn UTF-8.
Referencia
editUTF16String
editThe type UTF16String is an alias to the type WideString. In the LCL unit lclproc it is an alias to UnicodeString.
Reference
editWideString
editVariables of type WideString (used to represent unicode character strings in COM applications) resemble those of type UnicodeString, but unlike them they are not reference-counted. On Windows they are allocated with a special windows function which allows them to be used for OLE automation.
WideStrings consist of COM compatible UTF16 encoded bytes on Windows machines (UCS2 on Windows 2000), and they are encoded as plain UTF16 on Linux, Mac OS X and iOS.
| a | b | c | #0 | #0 | |||||||
| Length | |||||||||||
Referencia
editPShortString
editA variable of type PShortString is a pointer that points to the first byte of a ShortString-type variable (which defines the length of the ShortString).
| #3 | a | b | c |
| ^ |
Reference
editPAnsiString
editVariables of type PAnsiString are pointers to AnsiString-type variables. However, unlike PShortString-type variables they don't point to the first byte of the header, but to the first char of the AnsiString.
| a | b | c | #0 | ||||||||
| RefCount | Length | ^ | |||||||||
Reference
editPUnicodeString
editLas variables del tipo PUnicodeString son punteros a variables del tipo UnicodeString.
| a | b | c | #0 | #0 | |||||||||||
| RefCount | Length | ^ | |||||||||||||
Referencia
editPWideString
editLas variables de tipo PWideString son punteros. Apuntan al primer carácter de una variable tipo WideString.
| a | b | c | #0 | #0 | |||||||
| Length | ^ | ||||||||||
Referencías
editString constants
editIf you use only English constants your strings work the same with all types, on all platforms and all compiler versions. Non English strings can be loaded via resourcestrings or from files. If you want to use non English strings in code then you should read further.
There are various encodings for non English strings. By default Lazarus saves Pascal files as UTF-8 without BOM. UTF-8 supports the full Unicode range. That means all string constants are stored in UTF-8. Lazarus also supports to change the encoding of a file to other encoding, for example under Windows your local codepage. The Windows codepage is limited to your current language group.
| String Type, UTF-8 Source | With or without {$codepage utf8} | FPC 2.6.5 and below | FPC 2.7.1 and above | FPC 2.7.1+ with UTF8 as default CodePage |
|---|---|---|---|---|
| AnAnsiString:='ãü'; | Without | Needs UTF8ToAnsi in RTL/WinAPI. Ok in LCL | Needs UTF8ToAnsi in RTL/WinAPI. Ok in LCL | Ok in RTL/W-WinAPI/LCL. Needs UTF8ToWinCP in A-WinAPI. |
| AnAnsiString:='ãü'; | With | System cp ok in RTL/WinAPI. Needs SysToUTF8 in LCL | Ok in RTL/WinAPI/LCL. Mixing with other strings converts to system cp | Ok in RTL/W-WinAPI/LCL. Needs UTF8ToWinCP in A-WinAPI |
| AnUnicodeString:='ãü'; | Without | Wrong everywhere | Wrong everywhere | Wrong everywhere |
| AnUnicodeString:='ãü'; | With | System cp ok in RTL/WinAPI. Needs UTF8Encode in LCL | Ok in RTL/WinAPI/LCL. Mixing with other strings converts to system cp | Ok in RTL/W-WinAPI/LCL. Needs UTF8ToWinCP in A-WinAPI |
| AnUTF8String:='ãü'; | Without | Same as AnsiString | Wrong everywhere | Wrong everywhere |
| AnUTF8String:='ãü'; | With | Same as AnsiString | Ok in RTL/WinAPI/LCL. Mixing with other strings converts to system cp | Ok in RTL/W-WinAPI/LCL. Needs UTF8ToWinCP in A-WinAPI. |
- W-WinAPI = Windows API "W" functions, UTF-16
- A-WinAPI = Windows API non "W" functions, 8bit system code page
- System CP = The 8bit system code page of the OS. For example code page 1252.
const
c='ãü';
cstring: string = 'ãü'; // see AnAnsiString:='ãü';
var
s: string;
u: UnicodeString;
begin
s:=c; // same as s:='ãü';
s:=cstring; // does not change encoding
u:=c; // same as u:='ãü';
u:=cstring; // fpc 2.6.1: converts from system cp to UTF-16, fpc 2.7.1+: depends on encoding of cstring
end;