Conceptintro
String
Also called string, string type, character string, text string, str, String class.
A string is a sequence of characters that holds text. Each language defines what a character is, whether a string can change, and how text differs from bytes.
- Applies to
- core-languages
Idea
A program works with text all the time: names, messages, file paths, lines of input and the code of web pages. A string is the value that holds such text. It is a sequence of characters. It has a length, each character has a position, and a part of a string is also a string. Each language has a string type and literals for it, such as "café".
# A string is a sequence of characters. It has a length, and each character has an index.
s = "café"
print(len(s), s[0], s[-1], s[1:3])
# A Python string is immutable, so an assignment to one character fails.
try:
s[0] = "C"
except TypeError as e:
print(type(e).__name__)
# An operation that "changes" a string makes a new string.
t = "C" + s[1:]
print(s, t)
# Text and bytes are different types. Encoding turns text into bytes.
b = s.encode("utf-8")
print(b, len(b))
print(b.decode("utf-8") == s)
4 c é af
TypeError
café Café
b'caf\xc3\xa9' 5
True
The string "café" has 4 characters. Index 0 is c, index -1 is the last character, and the slice s[1:3] is the new string af. The assignment s[0] = "C" fails, because a Python string cannot change. To get Café, the program makes a new string from "C" and a slice, and s keeps its old value. The last lines show the difference between text and bytes. In UTF-8 the letter é takes 2 bytes, so the text has 4 characters but its bytes have a length of 5.
How it works
A sequence of characters. Wikipedia says that "a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable"1. The languages do not agree on what a character is, so they do not agree on what the length and the index of a string count:
- In Python, "Strings are immutable sequences of Unicode code points"2.
- In Java, "A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs", and "Index values refer to char code units"3. JavaScript and C# use UTF-16 code units in the same way. MDN says that JavaScript "Strings are represented fundamentally as sequences of UTF-16 code units"4.
- In Go, "A string value is a (possibly empty) sequence of bytes"5, and the bytes are UTF-8 by convention.
- In Rust, the type
String"is a growable, mutable, owned, UTF-8 encoded string type"6. - In C, "A null-terminated byte string (NTBS) is a sequence of nonzero bytes followed by a byte with value zero (the terminating null character)"7.
So "😀".length is 2 in JavaScript and Java, because the emoji is one code point but two UTF-16 code units. len("😀") is 1 in Python and 4 in Go. The pages string indexing and find the length of a string give the details.
Where the length is. A string must know where it ends. A C string has no stored length. The null character marks the end, so strlen must scan the bytes. Most other languages store the length next to the characters, so the string can hold any character, including a null character. A C++ std::string stores the length and also keeps a null character after the last element, because "*(s.begin() + s.size()) has value CharT() (a null terminator)"8. The page how strings are stored compares the layouts.
Immutable strings. In many languages a string value never changes. Java says: "Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared"3. Go says: "Strings are immutable: once created, it is impossible to change the contents of a string"5. C# says: "String objects are immutable: they can't be changed after they're created"9. Python, JavaScript and Kotlin strings are immutable too. An operation such as concatenation, replacement or a change of case returns a new string. Two variables can share one string with no risk, a string can be a key in a hash map, and two threads can read it with no lock.
Mutable strings. Code that builds text piece by piece needs a buffer that can change. Java has StringBuilder, "A mutable sequence of characters"10, and C# has System.Text.StringBuilder. Go has strings.Builder and []byte. Python has no mutable string type, but "str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments"2. In Rust, String owns a growable buffer on the heap11, and &str borrows a slice of one. In C, a string is an array of char, and the array can change. A C++ std::string is also mutable. See build a string efficiently.
Strings and bytes. Text is a sequence of characters, and the bytes of a file or of a network message are a sequence of numbers from 0 to 255. An encoding such as UTF-8 maps one to the other. Python keeps the two apart: "Bytes objects are immutable sequences of single bytes", and "bytearray objects are a mutable counterpart to bytes objects"2. Java and C# use byte[] and convert with getBytes and Encoding.UTF8. Go is different. Its strings hold bytes, and "a string holds arbitrary bytes. It is not required to hold Unicode text, UTF-8 text, or any other predefined format"12. Rust is strict in the other direction: a String is always valid UTF-8, and String::from_utf8 returns an error for bytes that are not. The C language does not separate text from bytes at all, so a char array can hold either.
Operations. The daily work with strings is a small set of operations, and the other pages of this sub-area show them in each tier 1 language: length, concatenation, join, split, substring, search, replace, comparison, case change and trim.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript uses the JavaScript string type, with the type string, and it adds string literal types and template literal types that limit a value to some strings. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has the immutable type String, which is java.lang.String on the JVM, with string templates, raw strings in triple quotes, StringBuilder and buildString. No example file exists because kotlinc is not installed. |
| SQL | Native | Standard SQL has the character string types CHARACTER, CHARACTER VARYING and CHARACTER LARGE OBJECT, the concatenation operator || and functions such as SUBSTRING and CHAR_LENGTH. No example file exists. |
| Bash | Native | The value of a Bash variable is a string, and parameter expansions such as ${#s}, ${s:i:n} and ${s/a/b} give its length, a substring and a replacement. No example file exists. |
| PowerShell | Native | PowerShell uses the .NET type System.String, with single-quoted literal strings and double-quoted strings that expand variables. No example file exists because pwsh is not installed. |
| HTML | Does not apply | The text content and the attribute values of an HTML document are text, but HTML has no data types, so it has no string type. |
| CSS | Native | CSS has the data type string, a sequence of characters in single or double quotes, which properties such as content and font-family take. |
| Regular expressions | Does not apply | A regular expression matches strings and parts of strings, but the pattern language has no string values of its own. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | str of code points, immutable; bytes and bytearray for binary data |
| JavaScript | native | primitive string of UTF-16 code units, immutable; TextEncoder for UTF-8 bytes |
| TypeScript | native | string, the JavaScript type, and string literal types such as "on" | "off" |
| Java | native | java.lang.String of UTF-16 char values, immutable; StringBuilder is mutable |
| Kotlin | native | kotlin.String, immutable, on the JVM java.lang.String; StringBuilder and buildString |
| C# | native | string (System.String) of UTF-16 char values, immutable; StringBuilder |
| Go | native | string, an immutable sequence of bytes, UTF-8 by convention; []byte, []rune and strings.Builder |
| Rust | native | str (used as &str), a borrowed UTF-8 slice; String, owned and growable |
| C | idiom | an array of char that ends with a null character; the functions of <string.h> |
| C++ | stdlib | std::string, a mutable sequence of char; std::string_view; C strings as well |
| Bash | native | every variable value is a string; ${#s}, ${s:i:n} and other parameter expansions |
| PowerShell | native | [string], the .NET System.String; single-quoted and expandable double-quoted strings |
| SQL | native | CHAR(n), VARCHAR(n) and CLOB, with || for concatenation |
| Regex | n/a | a pattern matches strings, but the pattern language has no string values |
| HTML | n/a | text content and attribute values are text, but HTML has no string type |
| CSS | native | the <string> data type, a quoted sequence of characters, as in content: "→" |
All general-purpose languages of the table have strings, but C has only a convention: an array of char and a null character at the end. The languages differ in three ways. The first is the unit of a character: a byte in C and Go, a UTF-16 code unit in Java, JavaScript and C#, and a code point in Python. The second is whether a string can change. The third is how strictly the language keeps text apart from bytes.
The example files show these differences. Python shows that += makes a new object, that a bytearray changes in place, and that str and bytes do not mix. JavaScript shows that length counts UTF-16 code units, that an assignment to an index throws in strict mode, and that a String object is not a primitive string. Java and C# count UTF-16 code units and code points, and change a StringBuilder in place. Go shows that len counts bytes, that range decodes runes, and that a string can hold bytes that are not valid UTF-8. Rust shows &str and String, a slice on a character boundary, and String::from_utf8. C shows the null character, strlen and sizeof, and the UTF-8 bytes of "café". C++ shows a mutable std::string that holds a null character, a std::string_view and c_str.
# str holds code points, bytes holds bytes, and bytearray is a mutable bytes.
s = "naïve 😀"
print(type(s).__name__, len(s), len(s.encode("utf-8")))
# += makes a new object. The old object does not change.
a = "ab"
b = a
a += "c"
print(a, b, a is b)
# bytearray can change in place.
ba = bytearray(b"cat")
ba[0] = ord("b")
print(ba, bytes(ba).decode("ascii"))
# str and bytes do not mix.
try:
"id: " + b"42"
except TypeError as e:
print(type(e).__name__)
# A string is also a sequence: it has in, iteration and slices.
print("ïv" in s, [c for c in "abc"], s[::-1])
str 7 11
abc ab False
bytearray(b'bat') bat
TypeError
True ['a', 'b', 'c'] 😀 evïan
- Verdict: native.
strholds code points, so"naïve 😀"has a length of 7, and its UTF-8 bytes have a length of 11.a += "c"makes a new object, andbstill refers to the old string. Abytearraychanges in place."id: " + b"42"raisesTypeError, because text and bytes do not mix. A string is also a sequence, within, iteration and slices.
#include <iostream>
#include <string>
#include <string_view>
using namespace std::string_literals;
int main() {
// std::string owns a mutable sequence of char.
std::string s = "cat";
s[0] = 'b';
s += "s";
std::cout << s << ' ' << s.size() << '\n';
// size() counts char values, which are UTF-8 bytes here.
std::string cafe = "café";
std::cout << cafe.size() << '\n';
// A std::string stores its length, so it can hold a null character.
std::string with_null = "ab\0cd"s;
std::cout << with_null.size() << ' ' << std::string("ab\0cd").size() << '\n';
// std::string_view refers to characters that another object owns.
std::string_view view = s;
view.remove_prefix(1);
std::cout << view << ' ' << s << '\n';
// c_str gives a null-terminated array for C functions.
std::cout << (s.c_str()[s.size()] == '\0') << '\n';
}
bats 4
5
5 2
ats bats
1
- Verdict: stdlib.
std::stringis a class of the standard library, and it is mutable.size()countscharvalues, which are 5 UTF-8 bytes for"café". The literal"ab\0cd"smakes a string of 5 characters with a null character inside, but a conversion from a C string stops at the null character. Astd::string_viewrefers to the characters ofswithout a copy.c_str()ends with a null character.
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
// A String holds UTF-16 code units. length() counts them.
String s = "naïve 😀";
System.out.println(s.length() + " " + s.codePointCount(0, s.length()));
// A String is immutable. concat and toUpperCase return new strings.
String t = s.concat("!");
System.out.println(s + " | " + t + " | " + s.toUpperCase(java.util.Locale.ROOT));
// StringBuilder is the mutable string type.
StringBuilder sb = new StringBuilder("cat");
sb.setCharAt(0, 'b');
sb.append("s");
System.out.println(sb + " " + sb.length());
// getBytes encodes the text. new String decodes it.
byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
System.out.println(utf8.length + " " + new String(utf8, StandardCharsets.UTF_8).equals(s));
// A char is one code unit, so the emoji is two chars.
char hi = s.charAt(6);
System.out.println(Character.isHighSurrogate(hi) + " " + Character.toChars(s.codePointAt(6)).length);
}
}
8 7
naïve 😀 | naïve 😀! | NAÏVE 😀
bats 4
11 true
true 2
- Verdict: native.
length()counts UTF-16 code units andcodePointCountcounts code points, so the emoji counts twice in the first number.concatandtoUpperCasereturn new strings, andsdoes not change. AStringBuilderchanges in place withsetCharAtandappend.getBytesencodes to 11 UTF-8 bytes.charAt(6)is the high surrogate of the emoji.
#include <stdio.h>
#include <string.h>
int main(void) {
/* A C string is an array of char that ends with a null character. */
char word[] = "cat";
printf("%zu %zu\n", strlen(word), sizeof word);
/* The array is mutable, so one char can change. */
word[0] = 'b';
printf("%s\n", word);
/* strlen counts bytes up to the first null character. */
char text[] = "ab\0cd";
printf("%zu %zu\n", strlen(text), sizeof text);
/* The bytes are UTF-8 when the source and the compiler use UTF-8. */
const char *s = "café";
printf("%zu:", strlen(s));
for (const unsigned char *p = (const unsigned char *)s; *p != '\0'; p++) {
printf(" %02X", *p);
}
printf("\n");
/* strcpy and strcat need room in the target array. */
char buf[16];
strcpy(buf, "cat");
strcat(buf, "s");
printf("%s %zu\n", buf, strlen(buf));
return 0;
}
3 4
bat
2 6
5: 63 61 66 C3 A9
cats 4
- Verdict: idiom. C has no string type. A string is an array of
charthat ends with a null character, sosizeof wordis 4 andstrlen(word)is 3. The array can change.strlenstops at the first null character, so it gives 2 for"ab\0cd". The bytes of"café"are UTF-8.strcpyandstrcatneed room in the target array.
using System.Text;
// A string holds UTF-16 code units. Length counts them.
string s = "naïve 😀";
Console.WriteLine($"{s.Length} {s.EnumerateRunes().Count()}");
// A string is immutable. Replace and ToUpperInvariant return new strings.
string t = s.Replace("naïve", "brave");
Console.WriteLine($"{s} | {t} | {s.ToUpperInvariant()}");
// string is a reference type, but == compares the characters.
string a = "ab";
string b = new string(new[] { 'a', 'b' });
Console.WriteLine($"{a == b} {ReferenceEquals(a, b)}");
// StringBuilder is the mutable string type.
var sb = new StringBuilder("cat");
sb[0] = 'b';
sb.Append('s');
Console.WriteLine($"{sb} {sb.Length}");
// Encoding.UTF8 converts between text and bytes.
byte[] utf8 = Encoding.UTF8.GetBytes(s);
Console.WriteLine($"{utf8.Length} {Encoding.UTF8.GetString(utf8) == s}");
8 7
naïve 😀 | brave 😀 | NAÏVE 😀
True False
bats 4
11 True
- Verdict: native.
Lengthcounts UTF-16 code units andEnumerateRunescounts code points.ReplaceandToUpperInvariantreturn new strings.==compares the characters of two strings, butReferenceEqualsshows that they are two objects. AStringBuilderchanges in place.Encoding.UTF8converts between text and bytes.
"use strict";
// A string is a primitive value made of UTF-16 code units.
const s = "naïve 😀";
console.log(typeof s, s.length, [...s].length);
// Strings are immutable. In strict mode an assignment to an index throws.
try {
s[0] = "N";
} catch (e) {
console.log(e.constructor.name);
}
// Methods return new strings and leave the old one as it was.
const upper = s.toUpperCase();
console.log(s, "|", upper);
// A String object is not a primitive string.
const boxed = new String("hi");
console.log(typeof boxed, boxed == "hi", boxed === "hi");
// TextEncoder gives the UTF-8 bytes of a string.
const bytes = new TextEncoder().encode(s);
console.log(bytes.constructor.name, bytes.length);
console.log(new TextDecoder().decode(bytes) === s);
string 8 7
TypeError
naïve 😀 | NAÏVE 😀
object true false
Uint8Array 11
true
- Verdict: native.
lengthcounts UTF-16 code units, so the string has a length of 8 but only 7 code points. In strict mode an assignment to an index throwsTypeError.toUpperCasereturns a new string.new String("hi")is an object:==converts it, and===sees a different type.TextEncodergives 11 UTF-8 bytes, andTextDecodergives the same text back.
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
// A string is a read-only sequence of bytes. len counts the bytes.
s := "naïve 😀"
fmt.Println(len(s), utf8.RuneCountInString(s))
// s[i] is a byte, and range decodes UTF-8 into runes.
fmt.Printf("%T %d\n", s[2], s[2])
var parts []string
for i, r := range "aï😀" {
parts = append(parts, fmt.Sprintf("%d:%c", i, r))
}
fmt.Println(strings.Join(parts, " "))
// A string cannot change. Convert to []byte, which is a copy.
b := []byte("cat")
b[0] = 'b'
fmt.Println(string(b))
// A string can hold bytes that are not valid UTF-8.
bad := "a\xffb"
fmt.Println(len(bad), utf8.ValidString(bad), utf8.ValidString(s))
// strings.Builder builds a string from parts.
var sb strings.Builder
for i := range 3 {
fmt.Fprintf(&sb, "%d;", i)
}
fmt.Println(sb.String())
}
11 7
uint8 195
0:a 1:ï 3:😀
bat
3 false true
0;1;2;
- Verdict: native.
lencounts the 11 bytes, andutf8.RuneCountInStringcounts 7 runes.s[2]is a byte (uint8), the first byte ofï.rangedecodes UTF-8, so the indexes jump from 1 to 3. A conversion to[]bytecopies the bytes, and the copy can change. A string can hold the byte0xFF, which is not valid UTF-8.strings.Builderbuilds a string from parts.
fn main() {
// A string literal is a &str: a borrowed slice of UTF-8 bytes.
let lit: &str = "naïve 😀";
println!("{} {}", lit.len(), lit.chars().count());
// String is the owned, growable type.
let mut owned = String::from("cat");
owned.push('s');
owned.push_str(" and dogs");
println!("{owned} {} {}", owned.len(), owned.capacity() >= owned.len());
// A &str can borrow part of a String, on character boundaries.
let first: &str = &owned[..4];
println!("{first}");
// Bytes become a String only if they are valid UTF-8.
let good = String::from_utf8(vec![0x63, 0x61, 0x66, 0xC3, 0xA9]);
let bad = String::from_utf8(vec![0x61, 0xFF]);
println!("{:?} {}", good, bad.is_err());
// as_bytes shows the UTF-8 bytes of the text.
println!("{:?}", "é".as_bytes());
}
11 7
cats and dogs 13 true
cats
Ok("café") true
[195, 169]
- Verdict: native. A literal is a
&str, andlencounts its 11 bytes.Stringis owned and growable, withpushandpush_str.&owned[..4]borrows a slice of theString.String::from_utf8accepts valid UTF-8 and returns an error for the byte0xFF.as_bytesshows the two bytes ofé.
Variations and related ideas
- Fixed-length and variable-length strings. Wikipedia describes "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"1. SQL
CHAR(n)is fixed-length and pads with spaces, andVARCHAR(n)has a maximum length. - Strings as lists. In Haskell, "String is an alias for a list of characters"13, so list functions work on strings, but each character takes a list cell.
- String views and slices. A view refers to characters that another value owns, so a substring needs no copy. Examples are Rust
&str, C++std::string_viewand Go substrings, which share the bytes of the original string. - Ropes. A rope stores a long string as a tree of short pieces, so an insertion in the middle does not copy the whole text.
- Byte strings. Python
bytes, Go[]byteand Cchararrays hold bytes that may or may not be text. Some programs, such as tools that read file names on Unix, must handle bytes that are not valid in any encoding. - Interned strings. Some languages keep one copy of equal string constants, so that a comparison of two references is enough. This is an implementation technique, and it is not part of the string type.
Pitfalls
- Length is not the number of characters.
"😀".lengthis 2 in JavaScript, Java and C#,len("é")is 2 in Go, and a flag emoji is two code points in every language. Decide which unit the program needs: bytes for storage, code points for most text processing, or grapheme clusters for what a user sees. - Repeated concatenation in a loop. An immutable string cannot grow, so
s = s + partcopies all ofseach time. Over n parts the copying grows with n². Use a builder or a join. ==on Java strings.==compares references, not characters, so two equal strings can givefalse. Useequals. See compare strings.- Mixing text and bytes. A program that decodes bytes with the wrong encoding gets wrong characters, for example
caféinstead ofcafé. Name the encoding at each boundary: file, network and database. - C strings without room.
strcpyandstrcatwrite past the end of the target array if it is too small, and the array needs one more byte for the null character. Also, "String literals are not modifiable", and "If a program attempts to modify the static array formed by a string literal, the behavior is undefined"14. - A null character inside data. The C string functions stop at the first null character. Bytes from a file or a network can contain one, so a C program must keep a length for such data.
Cost
A string of n characters takes memory in proportion to n, plus a small header. The header holds the length and, in most languages, a capacity or a hash. Reading the length is O(1) when the language stores it, and O(n) for strlen in C. Concatenation of two strings copies both, so it is O(n + m). A loop that appends n short parts to an immutable string is O(n²) in total, and a builder with a growing buffer makes it O(n). Access by index is O(1) for fixed-size units, such as bytes in Go and UTF-16 code units in Java. Access by code point in a UTF-8 string is O(n), because the program must decode the bytes before the index. Immutable strings save copies when code shares them, and they can cache their hash code.
History
Strings came from mathematics and logic, where a string is "a sequence of symbols or linguistic elements in a definite order"1. In programming, 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 1960s1. COMIT was "developed on the IBM 700/7000 series computers by Victor Yngve, University of Chicago, and collaborators at MIT from 1957 to 1965", for research in machine translation15.
The two common layouts of early strings come from two languages. In C, the null character ends a string, "a convention used and perpetuated by the popular C programming language"1. Many Pascal dialects store the length in the first byte, and "Storing the string length as byte limits the maximum string length to 255"1.
For a long time a character was one byte, but Unicode changed this. Java, JavaScript and C# chose 16-bit characters. Python 3.0, released on December 3, 2008, split text from bytes: "Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings"16, and "The type used to hold text is str, the type used to hold data is bytes"16. Go and Rust chose UTF-8. Rob Pike's article on Go strings from 2013 states that "Go source code is always UTF-8"12, and the Rust book says that "A String is a wrapper over a Vec"6.
References
- String (computer science), Wikipedia, Introduction; History; String length; Null-terminated; Length-prefixed
- Built-in Types, Python documentation, Text Sequence Type - str; Bytes Objects; Bytearray Objects
- Class String, Java SE 25 API, Class description
- String, MDN Web Docs, UTF-16 characters, Unicode code points, and grapheme clusters
- The Go Programming Language Specification, String types
- The Rust Programming Language, 8.2 Storing UTF-8 Encoded Text with Strings, Defining Strings; Internal Representation
- Null-terminated byte strings, C reference, cppreference.com, Introduction
- std::basic_string, C++ reference, cppreference.com, Introduction
- Strings and string literals, C# programming guide, Introduction; Immutability of strings
- Class StringBuilder, Java SE 25 API, Class description
- Struct String, The Rust Standard Library, Description
- Rob Pike, Strings, bytes, runes and characters in Go, The Go Blog (2013), What is a string; UTF-8 and string literals
- Prelude, Haskell base library, type String
- String literals, C reference, cppreference.com, Notes
- COMIT, Wikipedia, Introduction
- What's New In Python 3.0, Python documentation, Text Vs. Data Instead Of Unicode Vs. 8-bit
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag K7SNNX Edit this page History Report an error Markdown