In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). A string is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding. More general, string may also denote a sequence (or list) of data other than just characters.
Depending on the programming language and precise data type used, a variable declared to be a string may either cause storage in memory to be statically allocated for a predetermined maximum length or employ dynamic allocation to allow it to hold a variable number of elements.
When a string appears literally in source code, it is known as a string literal or an anonymous string.
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set called an alphabet.
Contents
Purpose
A primary purpose of strings is to store human-readable text, like words and sentences. Strings are used to communicate information from a computer program to the user of the program. A program may also accept string input from its user. Further, strings may store data expressed as characters yet not intended for human reading.
Example strings and their purposes:
A message like "file upload complete" is a string that software shows to end users. In the program's source code, this message would likely appear as a string literal.
User-entered text, like "I got a new job today" as a status update on a social media service. Instead of a string literal, the software would likely store this string in a database.
Alphabetical data, like "AGATGCCGT" representing nucleic acid sequences of DNA.
Computer settings or parameters, like "?action=edit" as a URL query string. Often these are intended to be somewhat human-readable, though their primary purpose is to communicate to computers.
The term string may also designate a sequence of data or computer records other than characters, like a "string of bits", but when used without qualification it refers to strings of characters.
History
Use of the word "string" to mean any items arranged in a line, series or succession dates back centuries. In 19th-century typesetting, compositors used the term "string" to denote a length of type printed on paper; the string would be measured to determine the compositor's pay.
Use of the word "string" to mean "a sequence of symbols or linguistic elements in a definite order" emerged from mathematics, symbolic logic, and linguistic theory to speak about the formal behavior of symbolic systems, setting aside the symbols' meaning.
For example, logician C. I. Lewis wrote in 1918:
A mathematical system is any set of strings of recognisable marks in which some of the strings are taken initially and the remainder derived from these by operations performed according to rules which are independent of any meaning assigned to the marks. That a system should consist of 'marks' instead of sounds or odours is immaterial.
According to Jean E. Sammet, "the first realistic string handling and pattern matching language" for computers was COMIT in the 1950s, followed by the SNOBOL language of the early 1960s.
String datatypes
A string datatype is a datatype modeled on the idea of a formal string. Strings are such an important and useful datatype that they are implemented in nearly every programming language. In some languages they are available as primitive types and in others as composite types. The syntax of most high-level programming languages allows for a string, usually quoted in some way, to represent an instance of a string datatype; such a meta-string is called a literal or string literal.
String length
Although formal strings can have an arbitrary finite length, the length of strings in real languages is often constrained to an artificial maximum. In general, there are two types of string datatypes: fixed-length strings, which have a fixed maximum length to be determined at compile time and which use the same amount of memory whether this maximum is needed or not, and variable-length strings, whose length is not arbitrarily fixed and which can use varying amounts of memory depending on the actual requirements at run time (see Memory management). Most strings in modern programming languages are variable-length strings. Of course, even variable-length strings are limited in length by the amount of available memory. The string length can be stored as a separate integer (which may put another artificial limit on the length) or implicitly through a termination character, usually a character value with all bits zero such as in C programming language. See also "Null-terminated" below.
Character encoding
String datatypes have historically allocated one byte per character, and, although the exact character set varied by region, character encodings were similar enough that programmers could often get away with ignoring this, since characters a program treated specially (such as period and space and comma) were in the same place in all the encodings a program would encounter. These character sets were typically based on ASCII or EBCDIC. If text in one encoding was displayed on a system using a different encoding, text was often mangled, though often somewhat readable and some computer users learned to read the mangled text.
Logographic languages such as Chinese, Japanese, and Korean (known collectively as CJK) need far more than 256 characters (the limit of a one 8-bit byte per-character encoding) for reasonable representation. The normal solutions involved keeping single-byte representations for ASCII and using two-byte representations for CJK ideographs. Use of these with existing code led to problems with matching and cutting of strings, the severity of which depended on how the character encoding was designed. Some encodings such as the EUC family guarantee that a byte value in the ASCII range will represent only that ASCII character, making the encoding safe for systems that use those characters as field separators. Other encodings such as ISO-2022 and Shift-JIS do not make such guarantees, making matching on byte codes unsafe. These encodings also were not "self-synchronizing", so that locating character boundaries required backing up to the start of a string, and pasting two strings together could result in corruption of the second string.
Unicode has simplified the picture somewhat. Most programming languages now have a datatype for Unicode strings. Unicode's preferred byte stream format UTF-8 is designed not to have the problems described above for older multibyte encodings. UTF-8, UTF-16 and UTF-32 require the programmer to know that the fixed-size code units are different from the "characters", the main difficulty currently is incorrectly designed APIs that attempt to hide this difference (UTF-32 does make code points fixed-sized, but these are not "characters" due to composing codes).
Implementations
Some languages, such as C++, Perl, and Ruby, normally allow the contents of a string to be changed after it has been created; these are termed mutable strings. In other languages, such as Java, JavaScript, Lua, Python, and Go, the value is fixed and a new string must be created if any alteration is to be made; these are termed immutable strings. Some of these languages with immutable strings also provide another type that is mutable, such as Java and .NET's StringBuilder, the thread-safe Java StringBuffer, and the Cocoa NSMutableString. Immutability brings advantages and disadvantages: while immutable strings may require inefficiently creating many copies, they are simpler and fully thread-safe.
Strings are typically implemented as arrays of bytes, characters, or code units, to allow fast access to individual units or substrings, including characters when they have a fixed length. A few languages such as Haskell implement them as linked lists instead.
Many high-level languages provide strings as a primitive data type, such as JavaScript and PHP, while most others provide them as a composite data type, some with special language support in writing literals, for example, Java and C#.
Some languages, such as C, Prolog and Erlang, avoid implementing a dedicated string datatype at all, instead adopting the convention of representing strings as lists of character codes. Even in programming languages having a dedicated string type, strings can usually be iterated as a sequence of character codes, like lists of integers or other values.
Representations
Representations of strings depend heavily on the choice of character repertoire and the method of character encoding. Older string implementations were designed to work with repertoire and encoding defined by ASCII, or more recent extensions like the ISO 8859 series. Modern implementations often use the extensive repertoire defined by Unicode along with a variety of complex encodings such as UTF-8 and UTF-16.
The term byte string usually indicates a general-purpose string of bytes, rather than strings of only (readable) characters, strings of bits, or such. Byte strings often imply that bytes can take any value and any data can be stored as-is, meaning that there should be no value interpreted as a termination value.
Most string implementations are very similar to variable-length arrays with the entries storing the character codes of corresponding characters. The principal difference is that, with certain encodings, a single logical character may take up more than one entry in the array. This happens, for example, with UTF-8, where single codes (UCS code points) can take anywhere from one to four bytes, and single characters can take an arbitrary number of codes. In these cases, the logical length of the string (number of characters) differs from the physical length of the array (number of bytes in use). UTF-32 avoids the first part of the problem.
The length of a string can be stored in a dope vector, separate from the storage holding the actual characters. The IBM PL/I (F) compiler used a string dope vector (SDV) for variable-length strings and for passing string parameters. The SDV contains a current length and a maximum length, and is not adjacent to the string proper. After PL/I (F), IBM dropped the SDV in favor of length-prefixed strings.
The length of a string can be stored implicitly by using a special terminating character; often this is the null character (NUL), which has all bits zero, a convention used and perpetuated by the popular C programming language. Hence, this representation is commonly referred to as a C string. This representation of an n-character string takes n + 1 space (1 for the terminator), and is thus an implicit data structure.
In terminated strings, the terminating code is not an allowable character in any string. Strings with length field do not have this limitation and can also store arbitrary binary data.
Security concerns
The differing memory layout and storage requirements of strings can affect the security of the program accessing the string data. String representations requiring a terminating character are commonly susceptible to buffer overflow problems if the terminating character is not present, caused by a coding error or an attacker deliberately altering the data. String representations adopting a separate length field are also susceptible if the length can be manipulated. In such cases, program code accessing the string data requires bounds checking to ensure that it does not inadvertently access or change data outside of the string memory limits.
String data is frequently obtained from user input to a program. As such, it is the responsibility of the program to validate the string to ensure that it represents the expected format. Performing limited or no validation of user input can cause a program to be vulnerable to code injection attacks.
Literal strings
Sometimes, strings need to be embedded inside a text file that is both human-readable and intended for consumption by a machine. This is needed in, for example, source code of programming languages, or in configuration files. In this case, the NUL character does not work well as a terminator since it is normally invisible (non-printable) and is difficult to input via a keyboard. Storing the string length would also be inconvenient as manual computation and tracking of the length is tedious and error-prone.
Two common representations are:
Surrounded by quotation marks (ASCII 0x22 double quote "str" or ASCII 0x27 single quote 'str'), used by most programming languages. To be able to include special characters such as the quotation mark itself, newline characters, or non-printable characters, escape sequences are often available, usually prefixed with the backslash character (ASCII 0x5C).
Terminated by a newline sequence, for example in Windows INI files.
Non-text strings
While character strings are very common uses of strings, a string in computer science may refer generically to any sequence of homogeneously typed data. A bit string or byte string, for example, may be used to represent non-textual binary data retrieved from a communications medium. This data may or may not be represented by a string-specific datatype, depending on the needs of the application, the desire of the programmer, and the capabilities of the programming language being used. If the programming language's string implementation is not 8-bit clean, data corruption may ensue.
C programmers draw a sharp distinction between a "string", aka a "string of characters", which by definition is always null terminated, vs. an "array of characters" which may be stored in the same array but is often not null terminated.
Using C string handling functions on such an array of characters often seems to work, but later leads to security problems.
String processing algorithms
There are many algorithms for processing strings, each with various trade-offs. Competing algorithms can be analyzed with respect to run time, storage requirements, and so forth. The name stringology was coined in 1984 by computer scientist Zvi Galil for the theory of algorithms and data structures used for string processing.
Some categories of algorithms include:
String searching algorithms for finding a given substring or pattern
String manipulation algorithms
Sorting algorithms
Regular expression algorithms
Parsing a string
Sequence mining
Advanced string algorithms often employ complex mechanisms and data structures, among them suffix trees and finite-state machines.
Character string-oriented languages and utilities
Character strings are such a useful datatype that several languages have been designed in order to make string processing applications easy to write. Examples include the following languages:
AWK
Icon
MUMPS
Perl
Rexx
Ruby
sed
SNOBOL
Tcl
TTM
Many Unix utilities perform simple string manipulations and can be used to easily program some powerful string processing algorithms. Files and finite streams may be viewed as strings.
Some APIs like Multimedia Control Interface, embedded SQL or printf use strings to hold commands that will be interpreted.
Many scripting programming languages, including Perl, Python, Ruby, and Tcl employ regular expressions to facilitate text operations. Perl is particularly noted for its regular expression use, and many other languages and applications implement Perl compatible regular expressions.
Some languages such as Perl and Ruby support string interpolation, which permits arbitrary expressions to be evaluated and included in string literals.
Character string functions
String functions are used to create strings or change the contents of a mutable string. They also are used to query information about a string. The set of functions and their names varies depending on the computer programming language.
The most basic example of a string function is the string length function – the function that returns the length of a string (not counting any terminator characters or any of the string's internal structural information) and does not modify the string. This function is often named length, len, or size. For example, length("hello world") would return 11. Another common function is concatenation, where a new string is created by appending two strings, often this is the + addition operator.
Some microprocessor's instruction set architectures contain direct support for string operations, such as block copy (e.g. In intel x86m REPNZ MOVSB).
Formal theory
Let
Σ
{\displaystyle \Sigma }
be a finite set of distinct, unambiguous symbols (alternatively called characters), called the alphabet. A string (or word or expression) over
Σ
{\displaystyle \Sigma }
is any finite sequence of symbols from
Σ
{\displaystyle \Sigma }
. For example, if
Σ
=
{
0
,
1
}
{\displaystyle \Sigma =\{{\texttt {0}},{\texttt {1}}\}}
, then
01011
{\displaystyle {\texttt {01011}}}
is a string over
Σ
{\displaystyle \Sigma }
.
The length of a string
s
{\displaystyle s}
is the number of symbols in
Concatenation and substrings
Concatenation is an important binary operation on
Σ
∗
{\displaystyle \Sigma ^{*}}
. For any two strings
s
{\displaystyle s}
and
t
{\displaystyle t}
in
Σ
∗
{\displaystyle \Sigma ^{*}}
, their concatenation is defined as the sequence of symbols in
s
{\displaystyle s}
followed by the sequence of characters in
t
{\displaystyle t}
, and is denoted
s
t
{\displaystyle st}
. For example, if
Σ
=
{
a
,
Prefixes and suffixes
A string
s
{\displaystyle s}
is said to be a prefix of
t
{\displaystyle t}
if there exists a string
u
{\displaystyle u}
such that
t
=
s
u
{\displaystyle t=su}
. If
u
{\displaystyle u}
is nonempty,
s
{\displaystyle s}
is said to be a proper prefix of
t
{\displaystyle t}
. Symmetrically, a string
s
{\displaystyle s}
is said to be a suffix of
t
{\displaystyle t}
if there exists a string
Reversal
The reverse of a string is a string with the same symbols but in reverse order. For example, if
s
=
abc
{\displaystyle s={\texttt {abc}}}
(where
a
{\displaystyle {\texttt {a}}}
,
b
{\displaystyle {\texttt {b}}}
, and
c
{\displaystyle {\texttt {c}}}
are symbols of the alphabet), then the reverse of
s
{\displaystyle s}
is
cba
{\displaystyle {\texttt {cba}}}
. A string that is the reverse of itself (e.g.,
s
=
madam
{\displaystyle s={\texttt {madam}}}
) is called a palindrome, which also includes the empty string and all strings of length
1
Rotations
A string
s
=
u
v
{\displaystyle s=uv}
is said to be a rotation of
t
{\displaystyle t}
if
t
=
v
u
{\displaystyle t=vu}
. For example, if
Σ
=
{
0
,
1
}
{\displaystyle \Sigma =\{{\texttt {0}},{\texttt {1}}\}}
the string
0011001
{\displaystyle {\texttt {0011001}}}
is a rotation of
0100110
{\displaystyle {\texttt {0100110}}}
, where
u
=
Lexicographical ordering
It is often useful to define an ordering on a set of strings. If the alphabet
Σ
{\displaystyle \Sigma }
has a total order (cf. alphabetical order) one can define a total order on
Σ
∗
{\displaystyle \Sigma ^{*}}
called lexicographical order. The lexicographical order is total if the alphabetical order is, but is not well-founded for any nontrivial alphabet, even if the alphabetical order is. For example, if
Σ
=
{
0
,
1
}
{\displaystyle \Sigma =\{{\texttt {0}},{\texttt {1}}\}}
and
0
<
1
{\displaystyle {\texttt {0}}<{\texttt {1}}}
, then the lexicographical order on
Σ
∗
{\displaystyle \Sigma ^{*}}
includes the relationships
String operations
A number of additional operations on strings commonly occur in the formal theory. These are given in the article on string operations.
Topology
Strings admit the following interpretation as nodes on a graph, where
k
{\displaystyle k}
is the number of symbols in
Σ
{\displaystyle \Sigma }
:
Fixed-length strings of length
n
{\displaystyle n}
can be viewed as the integer locations in an
n
{\displaystyle n}
-dimensional hypercube with sides of length
k
−
1
{\displaystyle k-1}
.
Variable-length strings (of finite length) can be viewed as nodes on a perfect
k
{\displaystyle k}
-ary tree.
Infinite strings (otherwise not considered here) can be viewed as infinite paths on a
k
{\displaystyle k}
-node complete graph.




