Methods
Constructs a string from another string.
Examples
Basic usage:
let s = String from;
assert_eq!;
Creates a new empty String
.
Given that the String
is empty, this will not allocate any initial buffer. While that means that this initial operation is very inexpensive, it may cause excessive allocation later when you add data. If you have an idea of how much data the String
will hold, consider the with_capacity
method to prevent excessive re-allocation.
Examples
Basic usage:
let s = String new;
Creates a new empty String
with at least the specified capacity.
String
s have an internal buffer to hold their data. The capacity is the length of that buffer, and can be queried with the capacity
method. This method creates an empty String
, but one with an initial buffer that can hold at least capacity
bytes. This is useful when you may be appending a bunch of data to the String
, reducing the number of reallocations it needs to do.
If the given capacity is 0
, no allocation will occur, and this method is identical to the new
method.
Examples
Basic usage:
let s = String with_capacity;
// The String contains no chars, even though it has capacity for more
assert_eq!;
// These are all done without reallocating...
let cap = s.capacity;
for _ in 0..10
assert_eq!;
// ...but this may make the string reallocate
s.push;
Returns the length of self
.
This length is in bytes, not char
s or graphemes. In other words, it might not be what a human considers the length of the string.
Examples
Basic usage:
let len = "foo".len;
assert_eq!;
assert_eq!; // fancy f!
assert_eq!;
Returns this String
's capacity, in bytes.
Examples
Basic usage:
let s = String with_capacity;
assert!;
Truncates this String
, removing all contents.
While this means the String
will have a length of zero, it does not touch its capacity.
Examples
Basic usage:
let s = "foo";
s.clear;
assert!;
assert_eq!;
assert_eq!;
Appends the given [char
] to the end of this String
.
Examples
Basic usage:
let s = "abc";
s.push;
s.push;
s.push;
assert_eq!;
Appends a given string slice onto the end of this String
.
Examples
Basic usage:
let s = "foo";
s.push_str;
assert_eq!;
Reserves capacity for at least additional
bytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling reserve
, capacity will be greater than or equal to self.len() + additional
. Does nothing if capacity is already sufficient.
Panics
Panics if the new capacity overflows [usize
].
Examples
Basic usage:
let s = String new;
s.reserve;
assert!;
This might not actually increase the capacity:
let s = String with_capacity;
s.push;
s.push;
// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity;
assert_eq!;
assert!;
// Since we already have at least an extra 8 capacity, calling this...
s.reserve;
// ... doesn't actually increase.
assert_eq!;
Reserves the minimum capacity for at least additional
bytes more than the current length. Unlike reserve
, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling reserve_exact
, capacity will be greater than or equal to self.len() + additional
. Does nothing if the capacity is already sufficient.
Panics
Panics if the new capacity overflows [usize
].
Examples
Basic usage:
let s = String new;
s.reserve_exact;
assert!;
This might not actually increase the capacity:
let s = String with_capacity;
s.push;
s.push;
// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity;
assert_eq!;
assert!;
// Since we already have at least an extra 8 capacity, calling this...
s.reserve_exact;
// ... doesn't actually increase.
assert_eq!;
Converts a vector of bytes to a String
.
A string ([String
]) is made of bytes ([u8
]), and a vector of bytes (Vec<u8>
) is made of bytes, so this function converts between the two. Not all byte slices are valid String
s, however: String
requires that it is valid UTF-8. from_utf8()
checks to ensure that the bytes are valid UTF-8, and then does the conversion.
If you are sure that the byte slice is valid UTF-8, and you don't want to incur the overhead of the validity check, there is an unsafe version of this function, from_utf8_unchecked
, which has the same behavior but skips the check.
The inverse of this method is into_bytes
.
Errors
Returns [Err
] if the slice is not UTF-8 with a description as to why the provided bytes are not UTF-8. The vector you moved in is also included.
Examples
Basic usage:
// some bytes, in a vector
let sparkle_heart = from_vec;
// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String from_utf8 .unwrap;
assert_eq!;
Incorrect bytes:
// some invalid bytes, in a vector
let sparkle_heart = from_vec;
assert!;
See the docs for [FromUtf8Error
] for more details on what you can do with this error.
Returns a byte slice of this String
's contents.
The inverse of this method is from_utf8
.
Examples
Basic usage:
let s = "hello";
assert_eq!;
assert!;
Returns a byte slice of this String
's contents while moving the string.
The inverse of this method is from_utf8
.
Examples
Basic usage:
let s = "hello";
assert_eq!;
assert!;
Clones the string and its underlying storage.
Examples
Basic usage:
let a = "h";
let b = a;
b.push;
// `a` and `b` refer to the same underlying string.
assert_eq!;
let c = b.clone;
c.push;
assert_ne!;
Shrinks the capacity of this String
to match its length.
Examples
Basic usage:
let s = "foo";
s.reserve;
assert!;
s.shrink_to_fit;
assert_eq!;
Access the character at the given byte index.
Returns None
if the index is out of bounds or not a character boundary.
Examples
let s = "おはよう";
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
An iterator over substrings of this string slice, separated by characters matched by a pattern.
The pattern can be a &str
, char
, a slice of char
s, or a function or closure that determines if a character matches.
Iterator behavior
The returned iterator will be a [DoubleEndedIterator
] if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char
, but not for &str
.
If the pattern allows a reverse search but its results might differ from a forward search, the rsplit
method can be used.
Examples
Simple patterns:
let v = "Mary had a little lamb".split .;
assert_eq!;
let v = "".split .;
assert_eq!;
let v = "lionXXtigerXleopard".split .;
assert_eq!;
let v = "lion::tiger::leopard".split .;
assert_eq!;
let v = "abc1def2ghi".split .;
assert_eq!;
let v = "lionXtigerXleopard".split .;
assert_eq!;
A more complex pattern, using a closure:
let v = "abc1defXghi".split .;
assert_eq!;
If a string contains multiple contiguous separators, you will end up with empty strings in the output:
let x = "||||a||b|c";
let d = x.split .;
assert_eq!;
Contiguous separators are separated by the empty string.
let x = "(///)";
let d = x.split .;
assert_eq!;
Separators at the start or end of a string are neighbored by empty strings.
let d = "010".split .;
assert_eq!;
When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.
let f = "rust".split .;
assert_eq!;
Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:
let x = " a b c";
let d = x.split .;
assert_eq!;
It does not give you:
assert_eq!;
Use split_whitespace
for this behavior.
Returns a string slice with leading and trailing whitespace removed.
'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space
, which includes newlines.
Examples
Basic usage:
let s = "\n Hello\tworld\t\n";
assert_eq!;
Returns a string slice with trailing whitespace removed.
'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space
, which includes newlines.
Text directionality
A string is a sequence of bytes. end
in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.
Examples
Basic usage:
let s = "\n Hello\tworld\t\n";
assert_eq!;
Directionality:
let s = " English ";
assert!;
let s = " עברית ";
assert!;
Replaces all matches of a pattern with another string.
replace
creates a new [String
], and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice.
Examples
Basic usage:
let s = "this is old";
assert_eq!;
assert_eq!;
When the pattern doesn't match, it returns this string slice as [String
]:
let s = "this is old";
assert_eq!;
Returns true
if self
has a length of zero bytes.
Examples
Basic usage:
let s = "";
assert!;
let s = "not empty";
assert!;
Returns an iterator over the char
s of a string slice.
As a string slice consists of valid UTF-8, we can iterate through a string slice by char
. This method returns such an iterator.
It's important to remember that char
represents a Unicode Scalar Value, and might not match your idea of what a 'character' is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust's standard library, check crates.io instead.
Examples
Basic usage:
let word = "goodbye";
let count = word.chars .count;
assert_eq!;
let chars = word.chars;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Remember, char
s might not match your intuition about characters:
let y = "y̆";
let chars = y.chars;
assert_eq!; // not 'y̆'
assert_eq!;
assert_eq!;
Returns a subslice of str
.
This is the non-panicking alternative to indexing the str
. Returns [None
] whenever equivalent indexing operation would panic.
Examples
let v = "🗻∈🌏";
assert_eq!;
// indices not on UTF-8 sequence boundaries
assert!;
assert!;
// out of bounds
assert!;
Parses this string into an integer.
Errors
Will return [Err
] if it's not possible to parse this string slice into an integer.
Examples
Basic usage
let four = "4".?;
assert_eq!;
Parses this string into a character.
Errors
Will return [Err
] if it's not possible to parse this string slice into an integer.
Examples
Basic usage
let a = "a".?;
assert_eq!;