Struct generic_str::StringBase [−][src]
#[repr(transparent)]pub struct StringBase<S: ?Sized> { /* fields omitted */ }
Implementations
Creates a new empty String32
.
Given that the String32
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 String32
will hold,
consider the with_capacity
method to prevent excessive
re-allocation.
Examples
Basic usage:
let s = String32::new();
Creates a new empty String
with a particular 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 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 mut s = String32::with_capacity(10);
// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);
// These are all done without reallocating...
let cap = s.capacity();
for _ in 0..10 {
s.push('a');
}
assert_eq!(s.capacity(), cap);
// ...but this may make the string reallocate
s.push('a');
Appends a given string slice onto the end of this String
.
Examples
Basic usage:
let mut s = String32::from("foo");
let t = String32::from("bar");
s.push_str32(&t);
assert_eq!(s, String32::from("foobar"));
Shortens this String
to the specified length.
If new_len
is greater than 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_len
does not lie on a char
boundary.
Examples
Basic usage:
let mut s = String32::from("hello");
s.truncate(2);
assert_eq!(s, String32::from("he"));
Removes a char
from this String
at a byte position and returns it.
This is an O(n) operation, as it requires copying every element in the buffer.
Panics
Panics if idx
is larger than or equal to the String
’s length,
or if it does not lie on a char
boundary.
Examples
Basic usage:
let mut s = String32::from("foo");
assert_eq!(s.remove(0), 'f');
assert_eq!(s.remove(1), 'o');
assert_eq!(s.remove(0), 'o');
Inserts a character into this String
at a byte position.
This is an O(n) operation as it requires copying every element in the buffer.
Panics
Panics if idx
is larger than the String
’s length, or if it does not
lie on a char
boundary.
Examples
Basic usage:
let mut s = String32::with_capacity(3);
s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');
assert_eq!(s, String32::from("foo"));
Returns a mutable reference to the contents of this String
.
Examples
Basic usage:
let mut s = String32::from("hello");
unsafe {
let vec = s.as_mut_vec();
assert_eq!(&['h', 'e', 'l', 'l', 'o'][..], &vec[..]);
vec.reverse();
}
assert_eq!(s, String32::from("olleh"));
pub fn split_off<B: ?Sized + StorageWithCapacity<Item = char>>(
&mut self,
at: usize
) -> OwnedString<char, B>
pub fn split_off<B: ?Sized + StorageWithCapacity<Item = char>>(
&mut self,
at: usize
) -> OwnedString<char, B>
Splits the string into two at the given byte index.
Returns a newly allocated String
. self
contains bytes [0, at)
, and
the returned String
contains bytes [at, len)
. at
must be on the
boundary of a UTF-8 code point.
Note that the capacity of self
does not change.
Panics
Panics if at
is not on a UTF-8
code point boundary, or if it is beyond the last
code point of the string.
Examples
let mut hello = String32::from("Hello, World!");
let world: String32 = hello.split_off(7);
assert_eq!(hello, String32::from("Hello, "));
assert_eq!(world, String32::from("World!"));
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 mut s = String32::from("foo");
let cap = s.capacity();
s.clear();
assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(cap, s.capacity());
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 a particular 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 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 mut s = String::with_capacity(10);
// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);
// These are all done without reallocating...
let cap = s.capacity();
for _ in 0..10 {
s.push('a');
}
assert_eq!(s.capacity(), cap);
// ...but this may make the string reallocate
s.push('a');
pub fn from_utf8(vec: GenericVec<S::Item, S>) -> Result<Self, FromUtf8Error<S>> where
S: Sized,
pub fn from_utf8(vec: GenericVec<S::Item, S>) -> Result<Self, FromUtf8Error<S>> where
S: Sized,
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.
This method will take care to not copy the vector, for efficiency’s sake.
If you need a &str
instead of a String
, consider
from_utf8
.
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 = vec![240, 159, 146, 150];
// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String::from_utf8(sparkle_heart.into()).unwrap();
assert_eq!(sparkle_heart, <&str>::from("💖"));
Incorrect bytes:
// some invalid bytes, in a vector
let sparkle_heart = vec![0, 159, 146, 150];
assert!(String::from_utf8(sparkle_heart.into()).is_err());
See the docs for FromUtf8Error
for more details on what you can do
with this error.
Converts a vector of bytes to a String
without 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 that String
s are valid UTF-8.
Examples
Basic usage:
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
let sparkle_heart = unsafe {
String::from_utf8_unchecked(sparkle_heart.into())
};
assert_eq!(sparkle_heart, <&str>::from("💖"));
Converts a String
into a byte vector.
This consumes the String
, so we do not need to copy its contents.
Examples
Basic usage:
let s = String::from("hello");
let bytes = s.into_bytes();
assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
Extracts a string slice containing the entire String
.
Examples
Basic usage:
let s = String::from("foo");
assert_eq!(s.as_str(), <&str>::from("foo"));
Converts a String
into a mutable string slice.
Examples
Basic usage:
let mut s = String::from("foobar");
let s_mut_str = s.as_mut_str();
s_mut_str.make_ascii_uppercase();
assert_eq!(s_mut_str, <&str>::from("FOOBAR"));
Appends a given string slice onto the end of this String
.
Examples
Basic usage:
let mut s = String::from("foo");
s.push_str("bar".into());
assert_eq!(s, <&str>::from("foobar"));
Ensures that this String
’s capacity is at least additional
bytes
larger than its length.
The capacity may be increased by more than additional
bytes if it
chooses, to prevent frequent reallocations.
Panics
Panics if the new capacity overflows usize
.
Examples
Basic usage:
let mut s = String::new();
s.reserve(10);
assert!(s.capacity() >= 10);
This may not actually increase the capacity:
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');
// s now has a length of 2 and a capacity of 10
assert_eq!(2, s.len());
assert_eq!(10, s.capacity());
// Since we already have an extra 8 capacity, calling this...
s.reserve(8);
// ... doesn't actually increase.
assert_eq!(10, s.capacity());
Tries to reserve capacity for at least additional
more elements to be inserted
in the given String
. The collection may reserve more space to avoid
frequent reallocations. After calling reserve
, capacity will be
greater than or equal to self.len() + additional
. Does nothing if
capacity is already sufficient.
Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Shortens this String
to the specified length.
If new_len
is greater than 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_len
does not lie on a char
boundary.
Examples
Basic usage:
let mut s = String::from("hello");
s.truncate(2);
assert_eq!(s, <&str>::from("he"));
Removes a char
from this String
at a byte position and returns it.
This is an O(n) operation, as it requires copying every element in the buffer.
Panics
Panics if idx
is larger than or equal to the String
’s length,
or if it does not lie on a char
boundary.
Examples
Basic usage:
let mut s = String::from("foo");
assert_eq!(s.remove(0), 'f');
assert_eq!(s.remove(1), 'o');
assert_eq!(s.remove(0), 'o');
Inserts a character into this String
at a byte position.
This is an O(n) operation as it requires copying every element in the buffer.
Panics
Panics if idx
is larger than the String
’s length, or if it does not
lie on a char
boundary.
Examples
Basic usage:
let mut s = String::with_capacity(3);
s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');
assert_eq!(s, <&str>::from("foo"));
Inserts a string slice into this String
at a byte position.
This is an O(n) operation as it requires copying every element in the buffer.
Panics
Panics if idx
is larger than the String
’s length, or if it does not
lie on a char
boundary.
Examples
Basic usage:
let mut s = String::from("bar");
s.insert_str(0, "foo");
assert_eq!(s, <&str>::from("foobar"));
Returns a mutable reference to the contents of this String
.
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 that String
s are valid UTF-8.
Examples
Basic usage:
let mut s = String::from("hello");
unsafe {
let vec = s.as_mut_vec();
assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
vec.reverse();
}
assert_eq!(s, <&str>::from("olleh"));
pub fn split_off<B: ?Sized + StorageWithCapacity<Item = u8>>(
&mut self,
at: usize
) -> StringBase<GenericVec<S::Item, B>>
pub fn split_off<B: ?Sized + StorageWithCapacity<Item = u8>>(
&mut self,
at: usize
) -> StringBase<GenericVec<S::Item, B>>
Splits the string into two at the given byte index.
Returns a newly allocated String
. self
contains bytes [0, at)
, and
the returned String
contains bytes [at, len)
. at
must be on the
boundary of a UTF-8 code point.
Note that the capacity of self
does not change.
Panics
Panics if at
is not on a UTF-8
code point boundary, or if it is beyond the last
code point of the string.
Examples
let mut hello = String::from("Hello, World!");
let world: String = hello.split_off(7);
assert_eq!(hello, <&str>::from("Hello, "));
assert_eq!(world, <&str>::from("World!"));
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 mut s = String::from("foo");
s.clear();
assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(3, s.capacity());
Returns true
if self
has a length of zero bytes.
Examples
Basic usage:
let s = String32::from("");
assert!(s.is_empty());
let s = String32::from("not empty");
assert!(!s.is_empty());
Converts a string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
char
. This pointer will be pointing to the first byte of the string
slice.
The caller must ensure that the returned pointer is never written to.
If you need to mutate the contents of the string slice, use as_mut_ptr
.
Examples
Basic usage:
let s = String32::from("Hello");
let ptr = s.as_ptr();
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
char
. This pointer will be pointing to the first byte of the string
slice.
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
char
. This pointer will be pointing to the first byte of the string
slice.
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
char
. This pointer will be pointing to the first byte of the string
slice.
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 = String32::from("🗻∈🌏");
assert_eq!(v.get(0..2).unwrap().to_owned(), String32::from("🗻∈"));
// out of bounds
assert!(v.get(..4).is_none());
Returns a mutable subslice of str
.
This is the non-panicking alternative to indexing the str
. Returns
None
whenever equivalent indexing operation would panic.
Examples
let mut v = String32::from("hello");
// correct length
assert!(v.get_mut(0..5).is_some());
// out of bounds
assert!(v.get_mut(..42).is_none());
{
let s = v.get_mut(0..2);
let s = s.map(|s| {
s.make_ascii_uppercase();
&*s
});
}
assert_eq!(v, String32::from("HEllo"));
Returns an unchecked subslice of str
.
This is the unchecked alternative to indexing the str
.
Safety
Callers of this function are responsible that these preconditions are satisfied:
- The starting index must not exceed the ending index;
- Indexes must be within bounds of the original slice;
- Indexes must lie on UTF-8 sequence boundaries.
Failing that, the returned string slice may reference invalid memory or
violate the invariants communicated by the str
type.
Examples
let v = "🗻∈🌏";
unsafe {
assert_eq!(v.get_unchecked(0..4), "🗻");
assert_eq!(v.get_unchecked(4..7), "∈");
assert_eq!(v.get_unchecked(7..11), "🌏");
}
Returns a mutable, unchecked subslice of str
.
This is the unchecked alternative to indexing the str
.
Safety
Callers of this function are responsible that these preconditions are satisfied:
- The starting index must not exceed the ending index;
- Indexes must be within bounds of the original slice;
- Indexes must lie on UTF-8 sequence boundaries.
Failing that, the returned string slice may reference invalid memory or
violate the invariants communicated by the str
type.
Examples
let mut v = String32::from("🗻∈🌏");
unsafe {
assert_eq!(*v.get_unchecked_mut(0..2), String32::from("🗻∈"));
}
Divide one string slice into two at an index.
The two slices returned go from the start of the string slice to mid
,
and from mid
to the end of the string slice.
To get mutable string slices instead, see the split_at_mut
method.
Panics
Panics if mid
is past the end of the last code point of the string slice.
Examples
Basic usage:
let s = String32::from("Per Martin-Löf");
let (first, last) = s.split_at(3);
assert_eq!(first.to_owned(), String32::from("Per"));
assert_eq!(last.to_owned(), String32::from(" Martin-Löf"));
Divide one mutable string slice into two at an index.
The argument, mid
, should be a byte offset from the start of the
string. It must also be on the boundary of a UTF-8 code point.
The two slices returned go from the start of the string slice to mid
,
and from mid
to the end of the string slice.
To get immutable string slices instead, see the split_at
method.
Panics
Panics if mid
is not on a UTF-8 code point boundary, or if it is
past the end of the last code point of the string slice.
Examples
Basic usage:
let mut s = String32::from("Per Martin-Löf");
{
let (first, last) = s.split_at_mut(3);
first.make_ascii_uppercase();
assert_eq!(first.to_owned(), String32::from("PER"));
assert_eq!(last.to_owned(), String32::from(" Martin-Löf"));
}
assert_eq!(s, String32::from("PER Martin-Löf"));
Converts this string to its ASCII upper case equivalent in-place.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.
To return a new uppercased value without modifying the existing one, use
to_ascii_uppercase()
.
Examples
let mut s = String32::from("Grüße, Jürgen ❤");
s.make_ascii_uppercase();
assert_eq!(s, String32::from("GRüßE, JüRGEN ❤"));
Converts this string to its ASCII lower case equivalent in-place.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.
To return a new lowercased value without modifying the existing one, use
to_ascii_lowercase()
.
Examples
let mut s = String32::from("GRÜßE, JÜRGEN ❤");
s.make_ascii_lowercase();
assert_eq!(s, String32::from("grÜße, jÜrgen ❤"));
Returns the length of self
.
This length is in bytes, not char
s or graphemes. In other words,
it may not be what a human considers the length of the string.
Examples
Basic usage:
let len = <&str>::from("foo").len();
assert_eq!(3, len);
assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
Returns true
if self
has a length of zero bytes.
Examples
Basic usage:
let s: &str = "".into();
assert!(s.is_empty());
let s: &str = "not empty".into();
assert!(!s.is_empty());
Checks that index
-th byte is the first byte in a UTF-8 code point
sequence or the end of the string.
The start and end of the string (when index == self.len()
) are
considered to be boundaries.
Returns false
if index
is greater than self.len()
.
Examples
let s: &str = "Löwe 老虎 Léopard".into();
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));
// second byte of `ö`
assert!(!s.is_char_boundary(2));
// third byte of `老`
assert!(!s.is_char_boundary(8));
Converts a mutable string slice to a mutable byte slice.
Safety
The caller must ensure that the content of the slice is valid UTF-8
before the borrow ends and the underlying str
is used.
Use of a str
whose contents are not valid UTF-8 is undefined behavior.
Examples
Basic usage:
let mut s = String::from("Hello");
let bytes = unsafe { s.as_bytes_mut() };
assert_eq!(bytes, b"Hello");
Mutability:
let mut s = String::from("🗻∈🌏");
unsafe {
let bytes = s.as_bytes_mut();
bytes[0] = 0xF0;
bytes[1] = 0x9F;
bytes[2] = 0x8D;
bytes[3] = 0x94;
}
assert_eq!(s, <&str>::from("🍔∈🌏"));
Converts a string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
u8
. This pointer will be pointing to the first byte of the string
slice.
The caller must ensure that the returned pointer is never written to.
If you need to mutate the contents of the string slice, use as_mut_ptr
.
Examples
Basic usage:
let s: &str = "Hello".into();
let ptr = s.as_ptr();
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to a
u8
. This pointer will be pointing to the first byte of the string
slice.
It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.
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 = String::from("🗻∈🌏");
assert_eq!(v.get(0..4), Some(<&str>::from("🗻")));
// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());
// out of bounds
assert!(v.get(..42).is_none());
Returns a mutable subslice of str
.
This is the non-panicking alternative to indexing the str
. Returns
None
whenever equivalent indexing operation would panic.
Examples
let mut v = String::from("hello");
// correct length
assert!(v.get_mut(0..5).is_some());
// out of bounds
assert!(v.get_mut(..42).is_none());
assert_eq!(v.get_mut(0..2).map(|v| &*v), Some(<&str>::from("he")));
assert_eq!(v, <&str>::from("hello"));
{
let s = v.get_mut(0..2);
let s = s.map(|s| {
s.make_ascii_uppercase();
&*s
});
assert_eq!(s, Some(<&str>::from("HE")));
}
assert_eq!(v, <&str>::from("HEllo"));
Returns an unchecked subslice of str
.
This is the unchecked alternative to indexing the str
.
Safety
Callers of this function are responsible that these preconditions are satisfied:
- The starting index must not exceed the ending index;
- Indexes must be within bounds of the original slice;
- Indexes must lie on UTF-8 sequence boundaries.
Failing that, the returned string slice may reference invalid memory or
violate the invariants communicated by the str
type.
Examples
let v = <&str>::from("🗻∈🌏");
unsafe {
assert_eq!(v.get_unchecked(0..4), <&str>::from("🗻"));
assert_eq!(v.get_unchecked(4..7), <&str>::from("∈"));
assert_eq!(v.get_unchecked(7..11), <&str>::from("🌏"));
}
Returns a mutable, unchecked subslice of str
.
This is the unchecked alternative to indexing the str
.
Safety
Callers of this function are responsible that these preconditions are satisfied:
- The starting index must not exceed the ending index;
- Indexes must be within bounds of the original slice;
- Indexes must lie on UTF-8 sequence boundaries.
Failing that, the returned string slice may reference invalid memory or
violate the invariants communicated by the str
type.
Examples
let mut v = String::from("🗻∈🌏");
unsafe {
assert_eq!(v.get_unchecked_mut(0..4), <&str>::from("🗻"));
assert_eq!(v.get_unchecked_mut(4..7), <&str>::from("∈"));
assert_eq!(v.get_unchecked_mut(7..11), <&str>::from("🌏"));
}
Divide one string slice into two at an index.
The argument, mid
, should be a byte offset from the start of the
string. It must also be on the boundary of a UTF-8 code point.
The two slices returned go from the start of the string slice to mid
,
and from mid
to the end of the string slice.
To get mutable string slices instead, see the split_at_mut
method.
Panics
Panics if mid
is not on a UTF-8 code point boundary, or if it is
past the end of the last code point of the string slice.
Examples
Basic usage:
let s: &str = "Per Martin-Löf".into();
let (first, last) = s.split_at(3);
assert_eq!(first, <&str>::from("Per"));
assert_eq!(last, <&str>::from(" Martin-Löf"));
Divide one mutable string slice into two at an index.
The argument, mid
, should be a byte offset from the start of the
string. It must also be on the boundary of a UTF-8 code point.
The two slices returned go from the start of the string slice to mid
,
and from mid
to the end of the string slice.
To get immutable string slices instead, see the split_at
method.
Panics
Panics if mid
is not on a UTF-8 code point boundary, or if it is
past the end of the last code point of the string slice.
Examples
Basic usage:
let mut s = String::from("Per Martin-Löf");
{
let (first, last) = s.split_at_mut(3);
first.make_ascii_uppercase();
assert_eq!(first, <&str>::from("PER"));
assert_eq!(last, <&str>::from(" Martin-Löf"));
}
assert_eq!(s, <&str>::from("PER Martin-Löf"));
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 may 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 = <&str>::from("goodbye");
let count = word.chars().count();
assert_eq!(7, count);
let mut chars = word.chars();
assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());
assert_eq!(None, chars.next());
Remember, char
s may not match your intuition about characters:
let y = "y̆";
let mut chars = y.chars();
assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());
assert_eq!(None, chars.next());
An iterator over the bytes of a string slice.
As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator.
Examples
Basic usage:
let mut bytes = <&str>::from("bors").bytes();
assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());
assert_eq!(None, bytes.next());
Checks if all characters in this string are within the ASCII range.
Examples
let ascii = <&str>::from("hello!\n");
let non_ascii = <&str>::from("Grüße, Jürgen ❤");
assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
Checks that two strings are an ASCII case-insensitive match.
Same as to_ascii_lowercase(a) == to_ascii_lowercase(b)
,
but without allocating and copying temporaries.
Examples
assert!(<&str>::from("Ferris").eq_ignore_ascii_case("FERRIS".into()));
assert!(<&str>::from("Ferrös").eq_ignore_ascii_case("FERRöS".into()));
assert!(!<&str>::from("Ferrös").eq_ignore_ascii_case("FERRÖS".into()));
Converts this string to its ASCII upper case equivalent in-place.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.
To return a new uppercased value without modifying the existing one, use
to_ascii_uppercase()
.
Examples
let mut s = String::from("Grüße, Jürgen ❤");
s.make_ascii_uppercase();
assert_eq!(s, <&str>::from("GRüßE, JüRGEN ❤"));
Converts this string to its ASCII lower case equivalent in-place.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.
To return a new lowercased value without modifying the existing one, use
to_ascii_lowercase()
.
Examples
let mut s = String::from("GRÜßE, JÜRGEN ❤");
s.make_ascii_lowercase();
assert_eq!(s, <&str>::from("grÜße, jÜrgen ❤"));
Returns the lowercase equivalent of this string slice, as a new String
.
‘Lowercase’ is defined according to the terms of the Unicode Derived Core Property
Lowercase
.
Since some characters can expand into multiple characters when changing
the case, this function returns a String
instead of modifying the
parameter in-place.
Examples
Basic usage:
let s = <&str>::from("HELLO");
assert_eq!(s.to_lowercase(), <&str>::from("hello"));
A tricky example, with sigma:
let sigma = <&str>::from("Σ");
assert_eq!(sigma.to_lowercase(), <&str>::from("σ"));
// but at the end of a word, it's ς, not σ:
let odysseus = <&str>::from("ὈΔΥΣΣΕΎΣ");
assert_eq!(odysseus.to_lowercase(), <&str>::from("ὀδυσσεύς"));
Languages without case are not changed:
let new_year = <&str>::from("农历新年");
assert_eq!(new_year, new_year.to_lowercase());
Returns the uppercase equivalent of this string slice, as a new String
.
‘Uppercase’ is defined according to the terms of the Unicode Derived Core Property
Uppercase
.
Since some characters can expand into multiple characters when changing
the case, this function returns a String
instead of modifying the
parameter in-place.
Examples
Basic usage:
let s = <&str>::from("hello");
assert_eq!(s.to_uppercase(), <&str>::from("HELLO"));
Scripts without case are not changed:
let new_year = <&str>::from("农历新年");
assert_eq!(new_year, new_year.to_uppercase());
One character can become multiple:
let s = <&str>::from("tschüß");
assert_eq!(s.to_uppercase(), <&str>::from("TSCHÜSS"));
Creates a new empty String
with a particular storage backend.
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 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 mut s = String::with_capacity(10);
// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);
// These are all done without reallocating...
let cap = s.capacity();
for _ in 0..10 {
s.push('a');
}
assert_eq!(s.capacity(), cap);
// ...but this may make the string reallocate
s.push('a');
Trait Implementations
Performs the +=
operation. Read more
Performs the +=
operation. Read more
Performs the conversion.
Performs the conversion.
Returns the “default value” for a type. Read more
type Target = StringBase<T::Target>
type Target = StringBase<T::Target>
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.
Performs the conversion.
impl<S: ?Sized + Storage> PartialEq<StringBase<GenericVec<<S as Storage>::Item, S>>> for StringSlice<S::Item> where
S::Item: PartialEq,
impl<S: ?Sized + Storage> PartialEq<StringBase<GenericVec<<S as Storage>::Item, S>>> for StringSlice<S::Item> where
S::Item: PartialEq,
impl<S: ?Sized + Storage> PartialEq<StringBase<GenericVec<<S as Storage>::Item, S>>> for &StringSlice<S::Item> where
S::Item: PartialEq,
impl<S: ?Sized + Storage> PartialEq<StringBase<GenericVec<<S as Storage>::Item, S>>> for &StringSlice<S::Item> where
S::Item: PartialEq,
impl<S: ?Sized + Storage, T: ?Sized + Storage> PartialEq<StringBase<GenericVec<<T as Storage>::Item, T>>> for StringBase<GenericVec<S::Item, S>> where
GenericVec<S::Item, S>: PartialEq<GenericVec<T::Item, T>>,
impl<S: ?Sized + Storage, T: ?Sized + Storage> PartialEq<StringBase<GenericVec<<T as Storage>::Item, T>>> for StringBase<GenericVec<S::Item, S>> where
GenericVec<S::Item, S>: PartialEq<GenericVec<T::Item, T>>,
impl<S: ?Sized + Storage> PartialOrd<&'_ StringBase<[<S as Storage>::Item]>> for OwnedString<S::Item, S> where
S::Item: PartialOrd,
impl<S: ?Sized + Storage> PartialOrd<&'_ StringBase<[<S as Storage>::Item]>> for OwnedString<S::Item, S> where
S::Item: PartialOrd,
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
impl<S: ?Sized + Storage> PartialOrd<StringBase<[<S as Storage>::Item]>> for OwnedString<S::Item, S> where
S::Item: PartialOrd,
impl<S: ?Sized + Storage> PartialOrd<StringBase<[<S as Storage>::Item]>> for OwnedString<S::Item, S> where
S::Item: PartialOrd,
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
impl<S: ?Sized + Storage> PartialOrd<StringBase<GenericVec<<S as Storage>::Item, S>>> for StringSlice<S::Item> where
S::Item: PartialOrd,
impl<S: ?Sized + Storage> PartialOrd<StringBase<GenericVec<<S as Storage>::Item, S>>> for StringSlice<S::Item> where
S::Item: PartialOrd,
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
impl<S: ?Sized + Storage> PartialOrd<StringBase<GenericVec<<S as Storage>::Item, S>>> for &StringSlice<S::Item> where
S::Item: PartialOrd,
impl<S: ?Sized + Storage> PartialOrd<StringBase<GenericVec<<S as Storage>::Item, S>>> for &StringSlice<S::Item> where
S::Item: PartialOrd,
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
impl<S: ?Sized + Storage, T: ?Sized + Storage> PartialOrd<StringBase<GenericVec<<T as Storage>::Item, T>>> for OwnedString<S::Item, S> where
GenericVec<S::Item, S>: PartialOrd<GenericVec<T::Item, T>>,
impl<S: ?Sized + Storage, T: ?Sized + Storage> PartialOrd<StringBase<GenericVec<<T as Storage>::Item, T>>> for OwnedString<S::Item, S> where
GenericVec<S::Item, S>: PartialOrd<GenericVec<T::Item, T>>,
This method returns an ordering between self
and other
values if one exists. Read more
This method tests less than (for self
and other
) and is used by the <
operator. Read more
This method tests less than or equal to (for self
and other
) and is used by the <=
operator. Read more
This method tests greater than (for self
and other
) and is used by the >
operator. Read more
Implements substring slicing with syntax &self[..]
or &mut self[..]
.
Returns a slice of the whole string, i.e., returns &self
or &mut self
. Equivalent to &self[0 .. len]
or &mut self[0 .. len]
. Unlike
other indexing operations, this can never panic.
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Equivalent to &self[0 .. len]
or &mut self[0 .. len]
.
type Output = StringBase<[char]>
type Output = StringBase<[char]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[begin .. end]
or &mut self[begin .. end]
.
Returns a slice of the given string from the byte range
[begin
, end
).
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Panics
Panics if begin > end
, or if end > len
.
type Output = StringBase<[char]>
type Output = StringBase<[char]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[.. end]
or &mut self[.. end]
.
Returns a slice of the given string from the char range [0
, end
).
Equivalent to &self[0 .. end]
or &mut self[0 .. end]
.
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Panics
Panics if end > len
.
type Output = StringBase<[char]>
type Output = StringBase<[char]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[begin ..]
or &mut self[begin ..]
.
Returns a slice of the given string from the char range [begin
,
len
). Equivalent to &self[begin .. len]
or &mut self[begin .. len]
.
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Panics
Panics if begin > len
.
type Output = StringBase<[char]>
type Output = StringBase<[char]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[..= end]
or &mut self[..= end]
.
Returns a slice of the given string from the byte range [0, end
].
Equivalent to &self [0 .. end + 1]
, except if end
has the maximum
value for usize
.
This operation is O(1).
Panics
Panics if end
does not point to the ending byte offset of a character
(end + 1
is either a starting byte offset as defined by
is_char_boundary
, or equal to len
), or if end >= len
.
type Output = StringBase<[char]>
type Output = StringBase<[char]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[..]
or &mut self[..]
.
Returns a slice of the whole string, i.e., returns &self
or &mut self
. Equivalent to &self[0 .. len]
or &mut self[0 .. len]
. Unlike
other indexing operations, this can never panic.
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Equivalent to &self[0 .. len]
or &mut self[0 .. len]
.
type Output = StringBase<[u8]>
type Output = StringBase<[u8]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[begin .. end]
or &mut self[begin .. end]
.
Returns a slice of the given string from the byte range
[begin
, end
).
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Panics
Panics if begin
or end
does not point to the starting byte offset of
a character (as defined by is_char_boundary
), if begin > end
, or if
end > len
.
Examples
let s = "Löwe 老虎 Léopard";
assert_eq!(&s[0 .. 1], "L");
assert_eq!(&s[1 .. 9], "öwe 老");
// these will panic:
// byte 2 lies within `ö`:
// &s[2 ..3];
// byte 8 lies within `老`
// &s[1 .. 8];
// byte 100 is outside the string
// &s[3 .. 100];
type Output = StringBase<[u8]>
type Output = StringBase<[u8]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[.. end]
or &mut self[.. end]
.
Returns a slice of the given string from the byte range [0
, end
).
Equivalent to &self[0 .. end]
or &mut self[0 .. end]
.
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Panics
Panics if end
does not point to the starting byte offset of a
character (as defined by is_char_boundary
), or if end > len
.
type Output = StringBase<[u8]>
type Output = StringBase<[u8]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[begin ..]
or &mut self[begin ..]
.
Returns a slice of the given string from the byte range [begin
,
len
). Equivalent to &self[begin .. len]
or &mut self[begin .. len]
.
This operation is O(1).
Prior to 1.20.0, these indexing operations were still supported by
direct implementation of Index
and IndexMut
.
Panics
Panics if begin
does not point to the starting byte offset of
a character (as defined by is_char_boundary
), or if begin > len
.
type Output = StringBase<[u8]>
type Output = StringBase<[u8]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
Implements substring slicing with syntax &self[..= end]
or &mut self[..= end]
.
Returns a slice of the given string from the byte range [0, end
].
Equivalent to &self [0 .. end + 1]
, except if end
has the maximum
value for usize
.
This operation is O(1).
Panics
Panics if end
does not point to the ending byte offset of a character
(end + 1
is either a starting byte offset as defined by
is_char_boundary
, or equal to len
), or if end >= len
.
type Output = StringBase<[u8]>
type Output = StringBase<[u8]>
The output type returned by methods.
slice_index_methods
)Returns a shared reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, if in bounds. Read more
slice_index_methods
)Returns a shared reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a mutable reference to the output at this location, without
performing any bounds checking.
Calling this method with an out-of-bounds index or a dangling slice
pointer
is undefined behavior even if the resulting reference is not used. Read more
slice_index_methods
)Returns a shared reference to the output at this location, panicking if out of bounds. Read more
type Owned = StringBase<HeapVec<T>>
type Owned = StringBase<HeapVec<T>>
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more
Auto Trait Implementations
impl<S: ?Sized> RefUnwindSafe for StringBase<S> where
S: RefUnwindSafe,
impl<S: ?Sized> Send for StringBase<S> where
S: Send,
impl<S: ?Sized> Sync for StringBase<S> where
S: Sync,
impl<S: ?Sized> Unpin for StringBase<S> where
S: Unpin,
impl<S: ?Sized> UnwindSafe for StringBase<S> where
S: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more