Understanding Text Data in Delphi Programming
Text representation forms the backbone of most programming applications, and Delphi provides developers with multiple mechanisms to store and manipulate character sequences. The language evolved significantly over its lifetime, introducing various string types to accommodate different encoding standards, memory constraints, and application requirements. Understanding which string type to employ in specific scenarios is essential for writing efficient, maintainable code that performs optimally across different platforms and use cases.
The Evolution of String Handling in Delphi
Early versions of Delphi inherited the string model from Turbo Pascal, which used fixed-length character arrays with a length indicator. This approach, while functional, imposed strict limitations on the maximum string size and memory efficiency. As the programming landscape evolved and international applications became commonplace, Delphi introduced additional string types to address these constraints. The language now supports multiple approaches to string storage, each with distinct advantages depending on the specific requirements of your application.
The modern Delphi environment provides developers with flexibility in choosing string types, but this flexibility comes with responsibility. Selecting inappropriate string types can lead to performance degradation, memory waste, or data corruption. Conversely, making informed decisions about string representation ensures your applications remain responsive and resource-efficient.
Legacy String Implementation: ShortString
ShortString represents the traditional approach to string storage in Delphi, maintaining backward compatibility with earlier Turbo Pascal implementations. This type stores character sequences with a maximum capacity of 255 characters, with the actual length stored in the first byte of the string structure. The memory footprint ranges from 2 to 256 bytes depending on the string content.
ShortString types prove particularly valuable when:
- Maintaining compatibility with legacy codebases that predate modern Delphi versions
- Working with fixed-size string declarations where length predictability simplifies memory management
- Interfacing with older Windows APIs or external libraries that expect Pascal-style strings
- Optimizing memory usage in resource-constrained environments
You can declare ShortString with explicit size constraints using bracketed notation. For example, a variable declared as String[50] creates a ShortString capable of holding up to 50 characters, with the actual memory consumption being 51 bytes (including the length indicator). This capability enables fine-grained control over memory allocation in performance-critical sections of code.
Single-Byte Character Encoding: AnsiString
AnsiString represents Delphi’s implementation of single-byte character encoding, supporting ANSI, DBCS (Double-Byte Character Set), and MBCS (Multi-Byte Character Set) encodings. This string type provides virtually unlimited length capacity, supporting up to approximately 2^31 characters with memory requirements ranging from 4 bytes to 2GB.
Key characteristics of AnsiString include:
- Reference counting for automatic memory management and efficient string copying
- Dynamic resizing as content grows or shrinks
- Complete backward compatibility with C-style null-terminated strings
- Seamless integration with Windows API functions expecting ANSI character buffers
AnsiString served as the default string type in Delphi versions prior to 2009, making it the expected type in countless legacy applications and libraries. The reference counting mechanism employed by AnsiString reduces memory waste when multiple variables reference the same string content—the actual character data exists once in memory with multiple pointers referencing it. Only when modification occurs does Delphi create a separate copy, implementing the copy-on-write pattern.
International Character Support: Unicode Strings
Modern application development frequently requires support for non-Latin scripts, emoji, and international text representations. Delphi addresses this requirement through Unicode string types, which encode characters using multiple bytes per character unit, typically UTF-16 encoding.
UnicodeString: The Modern Standard
Beginning with Delphi 2009, UnicodeString became the default string type, fundamentally changing how Delphi handles text data. This type supports up to approximately 2^30 characters and requires between 4 bytes and 2GB of memory. The keyword “string” automatically resolves to UnicodeString in modern Delphi environments, though compiler directives can alter this behavior for backward compatibility purposes.
UnicodeString offers several advantages for contemporary development:
- Native support for the full Unicode character set, enabling truly international applications
- UTF-16 encoding that handles character representation efficiently
- Automatic memory management through reference counting
- Seamless interoperability with .NET and Windows Unicode APIs
- Superior performance characteristics for text-heavy applications
WideString: COM and Legacy Integration
WideString provides compatibility with COM (Component Object Model) interfaces and other systems expecting UTF-16 encoded character sequences. While functionally similar to UnicodeString, WideString maintains specific behavioral characteristics required for COM interoperability. However, the Delphi development community generally recommends UnicodeString for new applications, reserving WideString for specific COM integration scenarios.
WideString availability varies across Delphi platforms—desktop platforms support this type fully, but mobile platform compilers exclude it, encouraging developers to standardize on UnicodeString.
String Type Comparison Matrix
| Type | Maximum Length | Memory Range | Primary Use Case | Character Encoding |
|---|---|---|---|---|
| ShortString | 255 characters | 2–256 bytes | Legacy compatibility | Single-byte ANSI |
| AnsiString | ~2^31 characters | 4 bytes–2GB | ANSI applications | ANSI/DBCS/MBCS |
| UnicodeString | ~2^30 characters | 4 bytes–2GB | Modern development | UTF-16 Unicode |
| WideString | ~2^30 characters | 4 bytes–2GB | COM integration | UTF-16 Unicode |
Character-Level Data: Char and WideChar
Beyond full string types, Delphi provides character-specific data types for handling individual character values. The Char type represents a single character from the basic ANSI set, while WideChar accommodates characters from the extended Unicode character set. These types prove useful when parsing text character-by-character or when implementing custom string algorithms.
Character types enable straightforward conversion between textual representation and numeric codes. For instance, the Ord() function converts a character to its ASCII or Unicode value, allowing mathematical operations on character data. The Chr() function performs the inverse conversion, transforming numeric values back into their character equivalents.
String Assignment and Type Conversion
Delphi employs automatic type conversion when assigning strings of different types to variables. The compiler intelligently handles conversions between string types, maintaining data integrity in most scenarios. However, developers must exercise caution when converting from wide character sets (Unicode) to narrow character sets (ANSI), as this operation may result in data loss if the source string contains characters absent from the target character set.
String literals in source code automatically adopt the appropriate type based on context. When assigned to a UnicodeString variable, literals become Unicode strings. When passed to functions expecting AnsiString parameters, the compiler performs the necessary conversion. Explicit type casting provides additional control when automatic conversion proves insufficient.
Practical String Manipulation Operations
Delphi runtime libraries provide extensive string processing capabilities, enabling developers to accomplish common text operations efficiently. Understanding these functions simplifies string handling and promotes code clarity.
Determining String Dimensions
The Length() function returns the number of characters within a string, providing essential information for text processing algorithms. For Unicode strings, Length() returns the character count rather than byte count, abstracting away encoding complexity. The SizeOf() function, conversely, returns the memory bytes consumed by a variable—for non-ShortString types, this returns the pointer size rather than content size.
Extracting and Modifying Content
The Copy() function extracts a substring from a source string by specifying the starting position and desired length. The Insert() function embeds text at a specified position within a target string, expanding it as necessary. These operations support character-by-character access using array notation, enabling selective character examination or modification.
String Comparison Operations
Delphi string comparison follows standard ordering rules based on character position correspondence. When comparing strings of unequal length, the additional characters in the longer string are considered greater than the end of the shorter string. For example, ‘AB’ exceeds ‘A’ in comparison ordering. Case sensitivity applies to standard comparison operators—’ABC’ and ‘abc’ represent distinct values in comparisons.
Memory Management Considerations
Understanding string memory behavior prevents resource waste and application performance degradation. Reference counting, employed by AnsiString, UnicodeString, and WideString types, automatically manages memory allocation and deallocation. When multiple variables reference the same string content, Delphi maintains a single copy with reference counters tracking usage. Memory is freed only when the final reference disappears.
The SetLength() procedure enables dynamic resizing of string variables, expanding capacity when needed or truncating content when necessary. This procedure proves valuable when building strings incrementally or when string content changes significantly during program execution.
Compiler Directives and String Type Control
The {$H-} compiler directive provides a mechanism for reverting string behavior to ShortString semantics in legacy code scenarios. Normally unnecessary in modern development, this directive enables selective backward compatibility within specific code sections. Developers migrating older applications to current Delphi versions may temporarily employ this directive while updating code to utilize contemporary string types.
String Literals and Multi-Line Text
Delphi supports multiple approaches for representing string constants in source code. Simple string literals use single quotes for delimitation, with doubled single quotes representing apostrophes within the content. Multi-line string literals employ triple-quoted notation, enabling readable representation of lengthy text blocks without escape sequences. This capability proves particularly valuable when incorporating HTML, SQL, or configuration data directly in source code.
Frequently Asked Questions
Q: Which string type should I use in new Delphi applications?
A: UnicodeString is the recommended default for new applications developed with Delphi 2009 or later. It provides optimal support for international text, integrates seamlessly with modern APIs, and offers robust memory management. Use AnsiString only when interfacing with legacy systems requiring ANSI encoding, and reserve ShortString for specific backward compatibility scenarios.
Q: How does reference counting improve string performance?
A: Reference counting enables efficient string copying without duplicating content. When assigning a string variable to another, only the pointer is copied, with an internal counter tracking references. The actual character data duplicates only when modification occurs, implementing copy-on-write semantics. This approach reduces memory consumption and improves performance for string-intensive operations.
Q: Can I mix different string types in assignments?
A: Yes, the compiler automatically converts between compatible string types in assignments and expressions. However, passing strings by reference (using var or out parameters) requires exact type matching. Explicit casting can force conversions when necessary, though converting Unicode to ANSI may result in data loss.
Q: What’s the difference between Length() and SizeOf() for strings?
A: Length() returns the character count within the string, while SizeOf() returns memory bytes consumed by the variable. For dynamic string types, SizeOf() returns pointer size (typically 4 or 8 bytes), not content size. Only for ShortString does SizeOf() return accurate byte representation of content.
Q: Why would I use WideString instead of UnicodeString?
A: WideString maintains compatibility with COM (Component Object Model) interfaces and COM-based libraries. For non-COM applications and general development, UnicodeString is preferred as it offers superior performance and broader platform support.
References
- Strings and characters – Delphi Basics — Delphi Basics. Accessed 2026-04-04. http://delphibasics.50webs.com/Article/Name/Text.html
- String Types (Delphi) – RAD Studio — Embarcadero DocWiki. Accessed 2026-04-04. https://docwiki.embarcadero.com/RADStudio/Athens/en/String_Types_(Delphi)
- Working with Strings – Delphi – Elements Docs — Elements Compiler Documentation. Accessed 2026-04-04. https://docs.elementscompiler.com/Platforms/Delphi/Strings/
