Embarcadero Delphi                
            stringhe
        
        
            
    Ricerca…
Tipi di stringhe
Delphi ha i seguenti tipi di stringa (in ordine di popolarità):
| genere | Lunghezza massima | Dimensione minima | Descrizione | 
|---|---|---|---|
 string  |  2GB | 16 byte |  Una stringa gestita. Un alias per AnsiString tramite Delphi 2007 e un alias per UnicodeString partire da Delphi 2009.  | 
 UnicodeString  |  2GB | 16 byte | Una stringa gestita in formato UTF-16. | 
 AnsiString  |  2GB | 16 byte | Una stringa gestita in formato ANSI pre-Unicode. A partire da Delphi 2009, porta un indicatore di codice di pagina esplicito. | 
 UTF8String  |  2GB | 16 byte |  Una stringa gestita in formato UTF-8, implementata come AnsiString con una AnsiString UTF-8.  | 
 ShortString  |  255 caratteri | 2 byte | Una stringa legacy, non fissa, di lunghezza fissa, con poco overhead | 
 WideString  |  2GB | 4 byte |  Destinato all'interoperabilità COM, una stringa gestita in formato UTF-16. Equivalente al tipo BSTR Windows.  | 
 UnicodeString e AnsiString sono conteggiati di riferimento e copy-on-write (COW). 
 ShortString e WideString non sono conteggiate di riferimento e non hanno la semantica COW. 
stringhe
uses
  System.Character;
var
  S1, S2: string;
begin
  S1 := 'Foo';
  S2 := ToLower(S1); // Convert the string to lower-case
  S1 := ToUpper(S2); // Convert the string to upper-case
        caratteri
uses
  Character;
var
  C1, C2: Char;
begin
  C1 := 'F';
  C2 := ToLower(C1); // Convert the char to lower-case
  C1 := ToUpper(C2); // Convert the char to upper-case
  La clausola uses deve essere System.Character se la versione è XE2 o successiva. 
Maiuscolo e minuscolo
uses
  SysUtils;
var
  S1, S2: string;
begin
  S1 := 'Foo';
  S2 := LowerCase(S1); // S2 := 'foo';
  S1 := UpperCase(S2); // S1 := 'FOO';
        assegnazione
Assegnare una stringa a diversi tipi di stringhe e come si comporta l'ambiente di runtime per quanto riguarda loro. Assegnazione della memoria, conteggio dei riferimenti, accesso indicizzato ai caratteri e errori del compilatore descritti brevemente laddove applicabile.
var
  SS5: string[5]; {a shortstring of 5 chars + 1 length byte, no trailing `0`}
  WS: Widestring; {managed pointer, with a bit of compiler support}
  AS: ansistring; {ansistring with the default codepage of the system}
  US: unicodestring; {default string type}
  U8: UTF8string;//same as AnsiString(65001)
  A1251: ansistring(1251); {ansistring with codepage 1251: Cryllic set}
  RB: RawbyteString; {ansistring with codepage 0: no conversion set}
begin
  SS5:= 'test'; {S[0] = Length(SS254) = 4, S[1] = 't'...S[5] = undefined}
  SS5:= 'test1'; {S[0] = 5, S[5] = '1', S[6] is out of bounds}
  SS5:= 'test12'; {compile time error}
  WS:= 'test'; {WS now points to a constant unicodestring hard compiled into the data segment}
  US:= 'test'+IntToStr(1); {New unicode string is created with reference count = 1}
  WS:= US; {SysAllocateStr with datacopied to dest, US refcount = 1 !}
  AS:= US; {the UTF16 in US is converted to "extended" ascii taking into account the codepage in AS possibly losing data in the process}  
  U8:= US; {safe copy of US to U8, all data is converted from UTF16 into UTF8}
  RB:= US; {RB = 'test1'#0 i.e. conversion into RawByteString uses system default codepage}
  A1251:= RB; {no conversion takes place, only reference copied. Ref count incremented }
        Conteggio di riferimento
Il conteggio dei riferimenti sulle stringhe è sicuro per i thread. I blocchi e i gestori di eccezioni vengono utilizzati per salvaguardare il processo. Si consideri il seguente codice, con commenti che indicano dove il compilatore inserisce il codice al momento della compilazione per gestire i conteggi dei riferimenti:
procedure PassWithNoModifier(S: string);
// prologue: Increase reference count of S (if non-negative),
//           and enter a try-finally block
begin
  // Create a new string to hold the contents of S and 'X'. Assign the new string to S,
  // thereby reducing the reference count of the string S originally pointed to and
  // brining the reference count of the new string to 1.
  // The string that S originally referred to is not modified.
  S := S + 'X';
end;
// epilogue: Enter the `finally` section and decrease the reference count of S, which is
//           now the new string. That count will be zero, so the new string will be freed.
    
procedure PassWithConst(const S: string);
var
  TempStr: string;
// prologue: Clear TempStr and enter a try-finally block. No modification of the reference
//           count of string referred to by S.
begin
  // Compile-time error: S is const.
  S := S + 'X';
  // Create a new string to hold the contents of S and 'X'. TempStr gets a reference count
  // of 1, and reference count of S remains unchanged.
  TempStr := S + 'X';
end;
// epilogue: Enter the `finally` section and decrease the reference count of TempStr,
//           freeing TempStr because its reference count will be zero.
  Come mostrato sopra, l'introduzione di una stringa locale temporanea per contenere le modifiche a un parametro comporta lo stesso overhead di apportare modifiche direttamente a quel parametro. La dichiarazione di una stringa const evita solo il conteggio dei riferimenti quando il parametro stringa è veramente di sola lettura. Tuttavia, per evitare la fuoriuscita di dettagli di implementazione al di fuori di una funzione, è consigliabile utilizzare sempre uno dei parametri const , var o out sul parametro stringa. 
codifiche
I tipi di stringa come UnicodeString, AnsiString, WideString e UTF8String vengono archiviati in una memoria utilizzando la rispettiva codifica (vedere Tipi di stringhe per ulteriori dettagli). Assegnare un tipo di stringa a un altro può comportare una conversione. La stringa di tipo è progettata per essere indipendente dalla codifica: non si dovrebbe mai usare la sua rappresentazione interna.
 La classe Sysutils.TEncoding fornisce il metodo GetBytes per la conversione da string a TBytes (matrice di byte) e GetString per la conversione di TBytes in string . La classe Sysutils.TEncoding fornisce inoltre molte codifiche predefinite come proprietà di classe. 
 Un modo per gestire le codifiche consiste nell'utilizzare solo il tipo di string nell'applicazione e utilizzare TEncoding ogni volta che è necessario utilizzare la codifica specifica, in genere nelle operazioni di I / O, nelle chiamate DLL, ecc. 
procedure EncodingExample;
var hello,response:string;
    dataout,datain:TBytes;
    expectedLength:integer;
    stringStream:TStringStream;
    stringList:TStringList;
     
begin
  hello := 'Hello World!Привет мир!';
  dataout := SysUtils.TEncoding.UTF8.GetBytes(hello); //Conversion to UTF8
  datain := SomeIOFunction(dataout); //This function expects input as TBytes in UTF8 and returns output as UTF8 encoded TBytes.
  response := SysUtils.TEncoding.UTF8.GetString(datain); //Convertsion from UTF8
  //In case you need to send text via pointer and length using specific encoding (used mostly for DLL calls)
  dataout := SysUtils.TEncoding.GetEncoding('ISO-8859-2').GetBytes(hello); //Conversion to ISO 8859-2
  DLLCall(addr(dataout[0]),length(dataout));
  //The same is for cases when you get text via pointer and length
  expectedLength := DLLCallToGetDataLength();
  setLength(datain,expectedLength);
  DLLCall(addr(datain[0]),length(datain));
  response := Sysutils.TEncoding.GetEncoding(1250).getString(datain);
   //TStringStream and TStringList can use encoding for I/O operations
   stringList:TStringList.create;
   stringList.text := hello;
   stringList.saveToFile('file.txt',SysUtils.TEncoding.Unicode);
   stringList.destroy;
   stringStream := TStringStream(hello,SysUtils.TEncoding.Unicode);
   stringStream.saveToFile('file2.txt');
   stringStream.Destroy;
end;