Struct String
struct String { ... }
A UTF-8βencoded, growable string.
String is the most common string type. It has ownership over the contents
of the string, stored in a heap-allocated buffer (see Representation).
It is closely related to its borrowed counterpart, the primitive str.
Examples
You can create a String from a literal string with String::from:
let hello = Stringfrom;
You can append a char to a String with the push method, and
append a &str with the push_str method:
let mut hello = Stringfrom;
hello.push;
hello.push_str;
If you have a vector of UTF-8 bytes, you can create a String from it with
the from_utf8 method:
// some bytes, in a vector
let sparkle_heart = vec!;
// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = Stringfrom_utf8.unwrap;
assert_eq!;
UTF-8
Strings are always valid UTF-8. If you need a non-UTF-8 string, consider
OsString. It is similar, but without the UTF-8 constraint. Because UTF-8
is a variable width encoding, Strings are typically smaller than an array of
the same chars:
// `s` is ASCII which represents each `char` as one byte
let s = "hello";
assert_eq!;
// A `char` array with the same contents would be longer because
// every `char` is four bytes
let s = ;
let size: usize = s.into_iter.map.sum;
assert_eq!;
// However, for non-ASCII strings, the difference will be smaller
// and sometimes they are the same
let s = "πππππ";
assert_eq!;
let s = ;
let size: usize = s.into_iter.map.sum;
assert_eq!;
This raises interesting questions as to how s[i] should work.
What should i be here? Several options include byte indices and
char indices but, because of UTF-8 encoding, only byte indices
would provide constant time indexing. Getting the ith char, for
example, is available using chars:
let s = "hello";
let third_character = s.chars.nth;
assert_eq!;
let s = "πππππ";
let third_character = s.chars.nth;
assert_eq!;
Next, what should s[i] return? Because indexing returns a reference
to underlying data it could be &u8, &[u8], or something similar.
Since we're only providing one index, &u8 makes the most sense but that
might not be what the user expects and can be explicitly achieved with
as_bytes():
// The first byte is 104 - the byte value of `'h'`
let s = "hello";
assert_eq!;
// or
assert_eq!;
// The first byte is 240 which isn't obviously useful
let s = "πππππ";
assert_eq!;
Due to these ambiguities/restrictions, indexing with a usize is simply
forbidden:
let s = "hello";
// The following will not compile!
println!("The first letter of s is {}", s[0]);
It is more clear, however, how &s[i..j] should work (that is,
indexing with a range). It should accept byte indices (to be constant-time)
and return a &str which is UTF-8 encoded. This is also called "string slicing".
Note this will panic if the byte indices provided are not character
boundaries - see is_char_boundary for more details. See the implementations
for SliceIndex<str> for more details on string slicing. For a non-panicking
version of string slicing, see get.
The bytes and chars methods return iterators over the bytes and
codepoints of the string, respectively. To iterate over codepoints along
with byte indices, use char_indices.
Deref
String implements Deref<Target = str>, and so inherits all of str's
methods. In addition, this means that you can pass a String to a
function which takes a &str by using an ampersand (&):
let s = Stringfrom;
takes_str;
This will create a &str from the String and pass it in. This
conversion is very inexpensive, and so generally, functions will accept
&strs as arguments unless they need a String for some specific
reason.
In certain cases Rust doesn't have enough information to make this
conversion, known as Deref coercion. In the following example a string
slice &'a str implements the trait TraitExample, and the function
example_func takes anything that implements the trait. In this case Rust
would need to make two implicit conversions, which Rust doesn't have the
means to do. For that reason, the following example will not compile.
trait TraitExample {}
impl<'a> TraitExample for &'a str {}
fn example_func<A: TraitExample>(example_arg: A) {}
let example_string = String::from("example_string");
example_func(&example_string);
There are two options that would work instead. The first would be to
change the line example_func(&example_string); to
example_func(example_string.as_str());, using the method as_str()
to explicitly extract the string slice containing the string. The second
way changes example_func(&example_string); to
example_func(&*example_string);. In this case we are dereferencing a
String to a str, then referencing the str back to
&str. The second way is more idiomatic, however both work to do the
conversion explicitly rather than relying on the implicit conversion.
Representation
A String is made up of three components: a pointer to some bytes, a
length, and a capacity. The pointer points to the internal buffer which String
uses to store its data. The length is the number of bytes currently stored
in the buffer, and the capacity is the size of the buffer in bytes. As such,
the length will always be less than or equal to the capacity.
This buffer is always stored on the heap.
You can look at these with the as_ptr, len, and capacity
methods:
let story = Stringfrom;
// Deconstruct the String into parts.
let = story.into_raw_parts;
// story has nineteen bytes
assert_eq!;
// We can re-build a String out of ptr, len, and capacity. This is all
// unsafe because we are responsible for making sure the components are
// valid:
let s = unsafe ;
assert_eq!;
If a String has enough capacity, adding elements to it will not
re-allocate. For example, consider this program:
let mut s = Stringnew;
println!;
for _ in 0..5
This will output the following:
0
8
16
16
32
32
At first, we have no memory allocated at all, but as we append to the
string, it increases its capacity appropriately. If we instead use the
with_capacity method to allocate the correct capacity initially:
let mut s = Stringwith_capacity;
println!;
for _ in 0..5
We end up with a different output:
25
25
25
25
25
25
Here, there's no need to allocate more memory inside the loop.
Implementations
impl String
const fn new() -> StringCreates a new empty
String.Given that the
Stringis 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 theStringwill hold, consider thewith_capacitymethod to prevent excessive re-allocation.Examples
let s = Stringnew;fn with_capacity(capacity: usize) -> StringCreates a new empty
Stringwith at least the specified capacity.Strings have an internal buffer to hold their data. The capacity is the length of that buffer, and can be queried with thecapacitymethod. This method creates an emptyString, but one with an initial buffer that can hold at leastcapacitybytes. This is useful when you may be appending a bunch of data to theString, 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 thenewmethod.Panics
Panics if the capacity exceeds
isize::MAXbytes.Examples
let mut s = Stringwith_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;fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError>Creates a new empty
Stringwith at least the specified capacity.Errors
Returns
Errif the capacity exceedsisize::MAXbytes, or if the memory allocator reports failure.fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>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 validStrings, however:Stringrequires 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.This method will take care to not copy the vector, for efficiency's sake.
If you need a
&strinstead of aString, considerstr::from_utf8.The inverse of this method is
into_bytes.Errors
Returns
Errif 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 = vec!; // We know these bytes are valid, so we'll use `unwrap()`. let sparkle_heart = Stringfrom_utf8.unwrap; assert_eq!;Incorrect bytes:
// some invalid bytes, in a vector let sparkle_heart = vec!; assert!;See the docs for
FromUtf8Errorfor more details on what you can do with this error.fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>Converts a slice of bytes to a string, including invalid characters.
Strings are made of bytes (
u8), and a slice of bytes (&[u8]) is made of bytes, so this function converts between the two. Not all byte slices are valid strings, however: strings are required to be valid UTF-8. During this conversion,from_utf8_lossy()will replace any invalid UTF-8 sequences withU+FFFD REPLACEMENT CHARACTER, which looks like this: οΏ½If you are sure that the byte slice is valid UTF-8, and you don't want to incur the overhead of the conversion, there is an unsafe version of this function,
from_utf8_unchecked, which has the same behavior but skips the checks.This function returns a
Cow<'a, str>. If our byte slice is invalid UTF-8, then we need to insert the replacement characters, which will change the size of the string, and hence, require aString. But if it's already valid UTF-8, we don't need a new allocation. This return type allows us to handle both cases.Examples
Basic usage:
// some bytes, in a vector let sparkle_heart = vec!; let sparkle_heart = Stringfrom_utf8_lossy; assert_eq!;Incorrect bytes:
// some invalid bytes let input = b"Hello \xF0\x90\x80World"; let output = Stringfrom_utf8_lossy; assert_eq!;fn from_utf8_lossy_owned(v: Vec<u8>) -> StringConverts a [
Vec<u8>] to aString, substituting invalid UTF-8 sequences with replacement characters.See
from_utf8_lossyfor more details.Note that this function does not guarantee reuse of the original
Vecallocation.Examples
Basic usage:
// some bytes, in a vector let sparkle_heart = vec!; let sparkle_heart = Stringfrom_utf8_lossy_owned; assert_eq!;Incorrect bytes:
// some invalid bytes let input: = b"Hello \xF0\x90\x80World".into; let output = Stringfrom_utf8_lossy_owned; assert_eq!;fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>Decode a native endian UTF-16βencoded vector
vinto aString, returningErrifvcontains any invalid data.Examples
// πmusic let v = &; assert_eq!; // πmu<invalid>ic let v = &; assert!;fn from_utf16_lossy(v: &[u16]) -> StringDecode a native endian UTF-16βencoded slice
vinto aString, replacing invalid data with the replacement character (U+FFFD).Unlike
from_utf8_lossywhich returns aCow<'a, str>,from_utf16_lossyreturns aStringsince the UTF-16 to UTF-8 conversion requires a memory allocation.Examples
// πmus<invalid>ic<invalid> let v = &; assert_eq!;fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error>Decode a UTF-16LEβencoded vector
vinto aString, returningErrifvcontains any invalid data.Examples
Basic usage:
// πmusic let v = &; assert_eq!; // πmu<invalid>ic let v = &; assert!;fn from_utf16le_lossy(v: &[u8]) -> StringDecode a UTF-16LEβencoded slice
vinto aString, replacing invalid data with the replacement character (U+FFFD).Unlike
from_utf8_lossywhich returns aCow<'a, str>,from_utf16le_lossyreturns aStringsince the UTF-16 to UTF-8 conversion requires a memory allocation.Examples
Basic usage:
// πmus<invalid>ic<invalid> let v = &; assert_eq!;fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error>Decode a UTF-16BEβencoded vector
vinto aString, returningErrifvcontains any invalid data.Examples
Basic usage:
// πmusic let v = &; assert_eq!; // πmu<invalid>ic let v = &; assert!;fn from_utf16be_lossy(v: &[u8]) -> StringDecode a UTF-16BEβencoded slice
vinto aString, replacing invalid data with the replacement character (U+FFFD).Unlike
from_utf8_lossywhich returns aCow<'a, str>,from_utf16le_lossyreturns aStringsince the UTF-16 to UTF-8 conversion requires a memory allocation.Examples
Basic usage:
// πmus<invalid>ic<invalid> let v = &; assert_eq!;fn into_raw_parts(self: Self) -> (*mut u8, usize, usize)Decomposes a
Stringinto its raw components:(pointer, length, capacity).Returns the raw pointer to the underlying data, the length of the string (in bytes), and the allocated capacity of the data (in bytes). These are the same arguments in the same order as the arguments to
from_raw_parts.After calling this function, the caller is responsible for the memory previously managed by the
String. The only way to do this is to convert the raw pointer, length, and capacity back into aStringwith thefrom_raw_partsfunction, allowing the destructor to perform the cleanup.Examples
let s = Stringfrom; let = s.into_raw_parts; let rebuilt = unsafe ; assert_eq!;unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> StringCreates a new
Stringfrom a pointer, a length and a capacity.Safety
This is highly unsafe, due to the number of invariants that aren't checked:
- all safety requirements for [
Vec::<u8>::from_raw_parts]. - all safety requirements for
String::from_utf8_unchecked.
Violating these may cause problems like corrupting the allocator's internal data structures. For example, it is normally not safe to build a
Stringfrom a pointer to a Cchararray containing UTF-8 unless you are certain that array was originally allocated by the Rust standard library's allocator.The ownership of
bufis effectively transferred to theStringwhich may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.Examples
unsafe- all safety requirements for [
unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> StringConverts a vector of bytes to a
Stringwithout checking that the string contains valid UTF-8.See the safe version,
from_utf8, for more details.Safety
This function is unsafe because it does not check that the bytes passed to it are valid UTF-8. If this constraint is violated, it may cause memory unsafety issues with future users of the
String, as the rest of the standard library assumes thatStrings are valid UTF-8.Examples
// some bytes, in a vector let sparkle_heart = vec!; let sparkle_heart = unsafe ; assert_eq!;const fn into_bytes(self: Self) -> Vec<u8>Converts a
Stringinto a byte vector.This consumes the
String, so we do not need to copy its contents.Examples
let s = Stringfrom; let bytes = s.into_bytes; assert_eq!;const fn as_str(self: &Self) -> &strExtracts a string slice containing the entire
String.Examples
let s = Stringfrom; assert_eq!;const fn as_mut_str(self: &mut Self) -> &mut strConverts a
Stringinto a mutable string slice.Examples
let mut s = Stringfrom; let s_mut_str = s.as_mut_str; s_mut_str.make_ascii_uppercase; assert_eq!;fn push_str(self: &mut Self, string: &str)Appends a given string slice onto the end of this
String.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut s = Stringfrom; s.push_str; assert_eq!;fn extend_from_within<R>(self: &mut Self, src: R) where R: RangeBounds<usize>Copies elements from
srcrange to the end of the string.Panics
Panics if the range has
start_bound > end_bound, if the range is bounded on either end and does not lie on acharboundary, or if the new capacity exceedsisize::MAXbytes.Examples
let mut string = Stringfrom; string.extend_from_within; assert_eq!; string.extend_from_within; assert_eq!; string.extend_from_within; assert_eq!;const fn capacity(self: &Self) -> usizeReturns this
String's capacity, in bytes.Examples
let s = Stringwith_capacity; assert!;fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalbytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After callingreserve, capacity will be greater than or equal toself.len() + additional. Does nothing if capacity is already sufficient.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
Basic usage:
let mut s = Stringnew; s.reserve; assert!;This might not actually increase the capacity:
let mut s = Stringwith_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!;fn reserve_exact(self: &mut Self, additional: usize)Reserves the minimum capacity for at least
additionalbytes more than the current length. Unlikereserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After callingreserve_exact, capacity will be greater than or equal toself.len() + additional. Does nothing if the capacity is already sufficient.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
Basic usage:
let mut s = Stringnew; s.reserve_exact; assert!;This might not actually increase the capacity:
let mut s = Stringwith_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!;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalbytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After callingtry_reserve, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use TryReserveError; # process_data.expect;fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve the minimum capacity for at least
additionalbytes more than the current length. Unliketry_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After callingtry_reserve_exact, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer
try_reserveif future insertions are expected.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use TryReserveError; # process_data.expect;fn shrink_to_fit(self: &mut Self)Shrinks the capacity of this
Stringto match its length.Examples
let mut s = Stringfrom; s.reserve; assert!; s.shrink_to_fit; assert_eq!;fn shrink_to(self: &mut Self, min_capacity: usize)Shrinks the capacity of this
Stringwith a lower bound.The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
Examples
let mut s = Stringfrom; s.reserve; assert!; s.shrink_to; assert!; s.shrink_to; assert!;fn push(self: &mut Self, ch: char)Appends the given
charto the end of thisString.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut s = Stringfrom; s.push; s.push; s.push; assert_eq!;const fn as_bytes(self: &Self) -> &[u8]Returns a byte slice of this
String's contents.The inverse of this method is
from_utf8.Examples
let s = Stringfrom; assert_eq!;fn truncate(self: &mut Self, new_len: usize)Shortens this
Stringto the specified length.If
new_lenis greater than or equal to the string's current length, this has no effect.Note that this method has no effect on the allocated capacity of the string
Panics
Panics if
new_lendoes not lie on acharboundary.Examples
let mut s = Stringfrom; s.truncate; assert_eq!;fn pop(self: &mut Self) -> Option<char>Removes the last character from the string buffer and returns it.
Returns
Noneif thisStringis empty.Examples
let mut s = Stringfrom; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn remove(self: &mut Self, idx: usize) -> charRemoves a
charfrom thisStringat byte positionidxand returns it.Copies all bytes after the removed char to new positions.
Note that calling this in a loop can result in quadratic behavior.
Panics
Panics if
idxis larger than or equal to theString's length, or if it does not lie on acharboundary.Examples
let mut s = Stringfrom; assert_eq!; assert_eq!; assert_eq!;fn remove_matches<P: Pattern>(self: &mut Self, pat: P)Remove all matches of pattern
patin theString.Examples
let mut s = Stringfrom; s.remove_matches; assert_eq!;Matches will be detected and removed iteratively, so in cases where patterns overlap, only the first pattern will be removed:
let mut s = Stringfrom; s.remove_matches; assert_eq!;fn retain<F>(self: &mut Self, f: F) where F: FnMut(char) -> boolRetains only the characters specified by the predicate.
In other words, remove all characters
csuch thatf(c)returnsfalse. This method operates in place, visiting each character exactly once in the original order, and preserves the order of the retained characters.Examples
let mut s = Stringfrom; s.retain; assert_eq!;Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.
let mut s = Stringfrom; let keep = ; let mut iter = keep.iter; s.retain; assert_eq!;fn insert(self: &mut Self, idx: usize, ch: char)Inserts a character into this
Stringat byte positionidx.Reallocates if
self.capacity()is insufficient, which may involve copying allself.capacity()bytes. Makes space for the insertion by copying all bytes of&self[idx..]to new positions.Note that calling this in a loop can result in quadratic behavior.
Panics
Panics if
idxis larger than theString's length, or if it does not lie on acharboundary.Examples
let mut s = Stringwith_capacity; s.insert; s.insert; s.insert; assert_eq!;fn insert_str(self: &mut Self, idx: usize, string: &str)Inserts a string slice into this
Stringat byte positionidx.Reallocates if
self.capacity()is insufficient, which may involve copying allself.capacity()bytes. Makes space for the insertion by copying all bytes of&self[idx..]to new positions.Note that calling this in a loop can result in quadratic behavior.
Panics
Panics if
idxis larger than theString's length, or if it does not lie on acharboundary.Examples
let mut s = Stringfrom; s.insert_str; assert_eq!;unsafe const fn as_mut_vec(self: &mut Self) -> &mut Vec<u8>Returns a mutable reference to the contents of this
String.Safety
This function is unsafe because the returned
&mut Vecallows writing bytes which are not valid UTF-8. If this constraint is violated, using the originalStringafter dropping the&mut Vecmay violate memory safety, as the rest of the standard library assumes thatStrings are valid UTF-8.Examples
let mut s = Stringfrom; unsafe assert_eq!;const fn len(self: &Self) -> usizeReturns the length of this
String, in bytes, notchars or graphemes. In other words, it might not be what a human considers the length of the string.Examples
let a = Stringfrom; assert_eq!; let fancy_f = Stringfrom; assert_eq!; assert_eq!;const fn is_empty(self: &Self) -> boolReturns
trueif thisStringhas a length of zero, andfalseotherwise.Examples
let mut v = Stringnew; assert!; v.push; assert!;fn split_off(self: &mut Self, at: usize) -> StringSplits the string into two at the given byte index.
Returns a newly allocated
String.selfcontains bytes[0, at), and the returnedStringcontains bytes[at, len).atmust be on the boundary of a UTF-8 code point.Note that the capacity of
selfdoes not change.Panics
Panics if
atis not on aUTF-8code point boundary, or if it is beyond the last code point of the string.Examples
#fn clear(self: &mut Self)Truncates this
String, removing all contents.While this means the
Stringwill have a length of zero, it does not touch its capacity.Examples
let mut s = Stringfrom; s.clear; assert!; assert_eq!; assert_eq!;fn drain<R>(self: &mut Self, range: R) -> Drain<'_> where R: RangeBounds<usize>Removes the specified range from the string in bulk, returning all removed characters as an iterator.
The returned iterator keeps a mutable borrow on the string to optimize its implementation.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and does not lie on acharboundary.Leaking
If the returned iterator goes out of scope without being dropped (due to
core::mem::forget, for example), the string may still contain a copy of any drained characters, or may have lost characters arbitrarily, including characters outside the range.Examples
let mut s = Stringfrom; let beta_offset = s.find.unwrap_or; // Remove the range up until the Ξ² from the string let t: String = s.drain.collect; assert_eq!; assert_eq!; // A full range clears the string, like `clear()` does s.drain; assert_eq!;fn into_chars(self: Self) -> IntoCharsConverts a
Stringinto an iterator over thechars of the string.As a string consists of valid UTF-8, we can iterate through a string by
char. This method returns such an iterator.It's important to remember that
charrepresents 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. That functionality is not provided by Rust's standard library, check crates.io instead.Examples
Basic usage:
let word = Stringfrom; let mut chars = word.into_chars; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Remember,
chars might not match your intuition about characters:let y = Stringfrom; let mut chars = y.into_chars; assert_eq!; // not 'yΜ' assert_eq!; assert_eq!;fn replace_range<R>(self: &mut Self, range: R, replace_with: &str) where R: RangeBounds<usize>Removes the specified range in the string, and replaces it with the given string. The given string doesn't need to be the same length as the range.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and does not lie on acharboundary.Examples
let mut s = Stringfrom; let beta_offset = s.find.unwrap_or; // Replace the range up until the Ξ² from the string s.replace_range; assert_eq!;fn replace_first<P: Pattern>(self: &mut Self, from: P, to: &str)Replaces the leftmost occurrence of a pattern with another string, in-place.
This method can be preferred over
string = string.replacen(..., 1);, as it can use theString's existing capacity to prevent a reallocation if sufficient space is available.Examples
Basic usage:
let mut s = Stringfrom; // Replace the leftmost β with a β s.replace_first; assert_eq!;fn replace_last<P: Pattern>(self: &mut Self, from: P, to: &str) where for<'a> <P as >::Searcher<'a>: core::str::pattern::ReverseSearcher<'a>Replaces the rightmost occurrence of a pattern with another string, in-place.
Examples
Basic usage:
let mut s = Stringfrom; // Replace the rightmost β with a β s.replace_last; assert_eq!;fn into_boxed_str(self: Self) -> Box<str>Converts this
Stringinto a[Box]<str>.Before doing the conversion, this method discards excess capacity like
shrink_to_fit. Note that this call may reallocate and copy the bytes of the string.Examples
let s = Stringfrom; let b = s.into_boxed_str;fn leak<'a>(self: Self) -> &'a mut strConsumes and leaks the
String, returning a mutable reference to the contents,&'a mut str.The caller has free choice over the returned lifetime, including
'static. Indeed, this function is ideally used for data that lives for the remainder of the program's life, as dropping the returned reference will cause a memory leak.It does not reallocate or shrink the
String, so the leaked allocation may include unused capacity that is not part of the returned slice. If you want to discard excess capacity, callinto_boxed_str, and thenBox::leakinstead. However, keep in mind that trimming the capacity may result in a reallocation and copy.Examples
let x = Stringfrom; let static_ref: &'static mut str = x.leak; assert_eq!; # // FIXME(https://github.com/rust-lang/miri/issues/3670): # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. # drop;
impl Add for String
fn add(self: Self, other: &str) -> String
impl AddAssign for String
fn add_assign(self: &mut Self, other: &str)
impl AsMut for String
fn as_mut(self: &mut Self) -> &mut str
impl AsRef for String
fn as_ref(self: &Self) -> &[u8]
impl AsRef for String
fn as_ref(self: &Self) -> &str
impl Borrow for crate::string::String
fn borrow(self: &Self) -> &str
impl BorrowMut for crate::string::String
fn borrow_mut(self: &mut Self) -> &mut str
impl Clone for String
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Clones the contents of
sourceintoself.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible.
impl Debug for String
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl Default for String
fn default() -> StringCreates an empty
String.
impl Deref for String
fn deref(self: &Self) -> &str
impl DerefMut for String
fn deref_mut(self: &mut Self) -> &mut str
impl DerefPure for String
impl Display for String
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl Eq for String
impl Extend for String
fn extend<I: IntoIterator<Item = core::ascii::Char>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, c: core::ascii::Char)
impl Extend for String
fn extend<I: IntoIterator<Item = char>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, c: char)fn extend_reserve(self: &mut Self, additional: usize)
impl Extend for String
fn extend<I: IntoIterator<Item = String>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, s: String)
impl Freeze for String
impl From for String
fn from(s: &str) -> StringConverts a
&strinto aString.The result is allocated on the heap.
impl From for String
fn from(s: Box<str>) -> StringConverts the given boxed
strslice to aString. It is notable that thestrslice is owned.Examples
let s1: String = Stringfrom; let s2: = s1.into_boxed_str; let s3: String = Stringfrom; assert_eq!
impl From for String
fn from(s: &mut str) -> StringConverts a
&mut strinto aString.The result is allocated on the heap.
impl From for String
fn from(s: &String) -> StringConverts a
&Stringinto aString.This clones
sand returns the clone.
impl From for String
fn from(c: char) -> SelfAllocates an owned
Stringfrom a single character.Example
let c: char = 'a'; let s: String = Stringfrom; assert_eq!;
impl FromIterator for String
fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String
impl FromIterator for String
fn from_iter<T: IntoIterator<Item = core::ascii::Char>>(iter: T) -> Self
impl FromIterator for String
fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> String
impl FromStr for String
fn from_str(s: &str) -> Result<String, <Self as >::Err>
impl Hash for String
fn hash<H: hash::Hasher>(self: &Self, hasher: &mut H)
impl Ord for String
fn cmp(self: &Self, other: &String) -> $crate::cmp::Ordering
impl PartialEq for String
fn eq(self: &Self, other: &String) -> bool
impl PartialOrd for String
fn partial_cmp(self: &Self, other: &String) -> $crate::option::Option<$crate::cmp::Ordering>
impl RefUnwindSafe for String
impl Send for String
impl StructuralPartialEq for String
impl Sync for String
impl TryFrom for String
fn try_from(bytes: Vec<u8>) -> Result<Self, <Self as >::Error>Converts the given [
Vec<u8>] into aStringif it contains valid UTF-8 data.Examples
let s1 = b"hello world".to_vec; let v1 = Stringtry_from.unwrap; assert_eq!;
impl TryFrom for crate::string::String
fn try_from(value: CString) -> Result<Self, <Self as >::Error>Converts a
CStringinto aStringif it contains valid UTF-8 data.This method is equivalent to
CString::into_string.
impl TryFrom for crate::string::String
fn try_from(s: ByteString) -> Result<Self, <Self as >::Error>
impl Unpin for String
impl UnwindSafe for String
impl Write for String
fn write_str(self: &mut Self, s: &str) -> fmt::Resultfn write_char(self: &mut Self, c: char) -> fmt::Result
impl<'a> Extend for String
fn extend<I: IntoIterator<Item = Cow<'a, str>>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, s: Cow<'a, str>)
impl<'a> Extend for String
fn extend<I: IntoIterator<Item = &'a str>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, s: &'a str)
impl<'a> Extend for String
fn extend<I: IntoIterator<Item = &'a char>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, c: &'a char)fn extend_reserve(self: &mut Self, additional: usize)
impl<'a> Extend for String
fn extend<I: IntoIterator<Item = &'a core::ascii::Char>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, c: &'a core::ascii::Char)
impl<'a> From for String
fn from(s: Cow<'a, str>) -> StringConverts a clone-on-write string to an owned instance of
String.This extracts the owned string, clones the string if it is not already owned.
Example
# use Cow; // If the string is not owned... let cow: = Borrowed; // It will allocate on the heap and copy the string. let owned: String = Stringfrom; assert_eq!;
impl<'a> FromIterator for String
fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> String
impl<'a> FromIterator for String
fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> String
impl<'a> FromIterator for String
fn from_iter<T: IntoIterator<Item = &'a core::ascii::Char>>(iter: T) -> Self
impl<'a> FromIterator for String
fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> String
impl<'a> PartialEq for crate::string::String
fn eq(self: &Self, other: &ByteStr) -> bool
impl<'a> PartialEq for crate::string::String
fn eq(self: &Self, other: &ByteString) -> bool
impl<'a> TryFrom for crate::string::String
fn try_from(s: &'a ByteStr) -> Result<Self, <Self as >::Error>
impl<'a, 'b> PartialEq for String
fn eq(self: &Self, other: &&'a str) -> boolfn ne(self: &Self, other: &&'a str) -> bool
impl<'a, 'b> PartialEq for String
fn eq(self: &Self, other: &str) -> boolfn ne(self: &Self, other: &str) -> bool
impl<'a, 'b> PartialEq for String
fn eq(self: &Self, other: &Cow<'a, str>) -> boolfn ne(self: &Self, other: &Cow<'a, str>) -> bool
impl<A: Allocator> Extend for String
fn extend<I: IntoIterator<Item = Box<str, A>>>(self: &mut Self, iter: I)
impl<A: Allocator> FromIterator for String
fn from_iter<I: IntoIterator<Item = Box<str, A>>>(iter: I) -> String
impl<I> Index for String
fn index(self: &Self, index: I) -> &<I as >::Output
impl<I> IndexMut for String
fn index_mut(self: &mut Self, index: I) -> &mut <I as >::Output
impl<P, T> Receiver for String
impl<T> Any for String
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for String
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for String
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for String
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for String
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for String
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> ToString for String
fn to_string(self: &Self) -> String
impl<T, U> Into for String
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for String
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for String
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>