Primitive Typestr
Expand description
String slices.
Thestr type, also called a ‘string slice’, is the most primitive stringtype. It is usually seen in its borrowed form,&str. It is also the typeof string literals,&'static str.
§Basic Usage
String literals are string slices:
Here we have declared a string slice initialized with a string literal.String literals have a static lifetime, which means the stringhello_worldis guaranteed to be valid for the duration of the entire program.We can explicitly specifyhello_world’s lifetime as well:
§Representation
A&str is made up of two components: a pointer to some bytes, and alength. You can look at these with theas_ptr andlen methods:
usestd::slice;usestd::str;letstory ="Once upon a time...";letptr = story.as_ptr();letlen = story.len();// story has nineteen bytesassert_eq!(19, len);// We can re-build a str out of ptr and len. This is all unsafe because// we are responsible for making sure the two components are valid:lets =unsafe{// First, we build a &[u8]...letslice = slice::from_raw_parts(ptr, len);// ... and then convert that slice into a string slicestr::from_utf8(slice)};assert_eq!(s,Ok(story));Note: This example shows the internals of&str.unsafe should not beused to get a string slice under normal circumstances. Useas_strinstead.
§Invariant
Rust libraries may assume that string slices are always valid UTF-8.
Constructing a non-UTF-8 string slice is not immediate undefined behavior, but any functioncalled on a string slice may assume that it is valid UTF-8, which means that a non-UTF-8 stringslice can lead to undefined behavior down the road.
Implementations§
Source§implstr
implstr
1.0.0 (const: 1.39.0) ·Sourcepub const fnis_empty(&self) ->bool
pub const fnis_empty(&self) ->bool
Returnstrue ifself has a length of zero bytes.
§Examples
1.87.0 (const: 1.87.0) ·Sourcepub const fnfrom_utf8(v: &[u8]) ->Result<&str,Utf8Error>
pub const fnfrom_utf8(v: &[u8]) ->Result<&str,Utf8Error>
Converts a slice of bytes to a string slice.
A string slice (&str) is made of bytes (u8), and a byte slice(&[u8]) is made of bytes, so this function converts betweenthe two. Not all byte slices are valid string slices, however:&str requiresthat it is valid UTF-8.from_utf8() checks to ensure that the bytes are validUTF-8, and then does the conversion.
If you are sure that the byte slice is valid UTF-8, and you don’t want toincur the overhead of the validity check, there is an unsafe version ofthis function,from_utf8_unchecked, which has the samebehavior but skips the check.
If you need aString instead of a&str, considerString::from_utf8.
Because you can stack-allocate a[u8; N], and you can take a&[u8] of it, this function is one way to have astack-allocated string. There is an example of this in theexamples section below.
§Errors
ReturnsErr if the slice is not UTF-8 with a description as to why theprovided slice is not UTF-8.
§Examples
Basic usage:
// some bytes, in a vectorletsparkle_heart =vec![240,159,146,150];// We can use the ? (try) operator to check if the bytes are validletsparkle_heart = str::from_utf8(&sparkle_heart)?;assert_eq!("💖", sparkle_heart);Incorrect bytes:
// some invalid bytes, in a vectorletsparkle_heart =vec![0,159,146,150];assert!(str::from_utf8(&sparkle_heart).is_err());See the docs forUtf8Error for more details on the kinds oferrors that can be returned.
A “stack allocated string”:
1.87.0 (const: 1.87.0) ·Sourcepub const fnfrom_utf8_mut(v: &mut [u8]) ->Result<&mutstr,Utf8Error>
pub const fnfrom_utf8_mut(v: &mut [u8]) ->Result<&mutstr,Utf8Error>
Converts a mutable slice of bytes to a mutable string slice.
§Examples
Basic usage:
// "Hello, Rust!" as a mutable vectorletmuthellorust =vec![72,101,108,108,111,44,32,82,117,115,116,33];// As we know these bytes are valid, we can use `unwrap()`letoutstr = str::from_utf8_mut(&muthellorust).unwrap();assert_eq!("Hello, Rust!", outstr);Incorrect bytes:
// Some invalid bytes in a mutable vectorletmutinvalid =vec![128,223];assert!(str::from_utf8_mut(&mutinvalid).is_err());See the docs forUtf8Error for more details on the kinds oferrors that can be returned.
1.87.0 (const: 1.87.0) ·Sourcepub const unsafe fnfrom_utf8_unchecked(v: &[u8]) -> &str
pub const unsafe fnfrom_utf8_unchecked(v: &[u8]) -> &str
1.87.0 (const: 1.87.0) ·Sourcepub const unsafe fnfrom_utf8_unchecked_mut(v: &mut [u8]) -> &mutstr
pub const unsafe fnfrom_utf8_unchecked_mut(v: &mut [u8]) -> &mutstr
Converts a slice of bytes to a string slice without checkingthat the string contains valid UTF-8; mutable version.
See the immutable version,from_utf8_unchecked() for documentation and safety requirements.
§Examples
Basic usage:
1.9.0 (const: 1.86.0) ·Sourcepub const fnis_char_boundary(&self, index:usize) ->bool
pub const fnis_char_boundary(&self, index:usize) ->bool
Checks thatindex-th byte is the first byte in a UTF-8 code pointsequence or the end of the string.
The start and end of the string (whenindex == self.len()) areconsidered to be boundaries.
Returnsfalse ifindex is greater thanself.len().
§Examples
1.91.0 (const: 1.91.0) ·Sourcepub const fnfloor_char_boundary(&self, index:usize) ->usize
pub const fnfloor_char_boundary(&self, index:usize) ->usize
Finds the closestx not exceedingindex whereis_char_boundary(x) istrue.
This method can help you truncate a string so that it’s still valid UTF-8, but doesn’texceed a given number of bytes. Note that this is done purely at the character leveland can still visually split graphemes, even though the underlying characters aren’tsplit. For example, the emoji 🧑🔬 (scientist) could be split so that the string onlyincludes 🧑 (person) instead.
§Examples
1.91.0 (const: 1.91.0) ·Sourcepub const fnceil_char_boundary(&self, index:usize) ->usize
pub const fnceil_char_boundary(&self, index:usize) ->usize
Finds the closestx not belowindex whereis_char_boundary(x) istrue.
Ifindex is greater than the length of the string, this returns the length of the string.
This method is the natural complement tofloor_char_boundary. See that methodfor more details.
§Examples
1.20.0 (const: 1.83.0) ·Sourcepub const unsafe fnas_bytes_mut(&mut self) -> &mut [u8]ⓘ
pub const unsafe fnas_bytes_mut(&mut self) -> &mut [u8]ⓘ
1.0.0 (const: 1.32.0) ·Sourcepub const fnas_ptr(&self) ->*constu8
pub const fnas_ptr(&self) ->*constu8
Converts a string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to au8. This pointer will be pointing to the first byte of the stringslice.
The caller must ensure that the returned pointer is never written to.If you need to mutate the contents of the string slice, useas_mut_ptr.
§Examples
1.36.0 (const: 1.83.0) ·Sourcepub const fnas_mut_ptr(&mut self) ->*mutu8
pub const fnas_mut_ptr(&mut self) ->*mutu8
Converts a mutable string slice to a raw pointer.
As string slices are a slice of bytes, the raw pointer points to au8. This pointer will be pointing to the first byte of the stringslice.
It is your responsibility to make sure that the string slice only getsmodified in a way that it remains valid UTF-8.
1.20.0 (const:unstable) ·Sourcepub fnget<I>(&self, i: I) ->Option<&<I asSliceIndex<str>>::Output>where I:SliceIndex<str>,
pub fnget<I>(&self, i: I) ->Option<&<I asSliceIndex<str>>::Output>where I:SliceIndex<str>,
1.20.0 (const:unstable) ·Sourcepub fnget_mut<I>( &mut self, i: I,) ->Option<&mut <I asSliceIndex<str>>::Output>where I:SliceIndex<str>,
pub fnget_mut<I>( &mut self, i: I,) ->Option<&mut <I asSliceIndex<str>>::Output>where I:SliceIndex<str>,
Returns a mutable subslice ofstr.
This is the non-panicking alternative to indexing thestr. ReturnsNone whenever equivalent indexing operation would panic.
§Examples
letmutv = String::from("hello");// correct lengthassert!(v.get_mut(0..5).is_some());// out of boundsassert!(v.get_mut(..42).is_none());assert_eq!(Some("he"), v.get_mut(0..2).map(|v|&*v));assert_eq!("hello", v);{lets = v.get_mut(0..2);lets = s.map(|s| { s.make_ascii_uppercase();&*s });assert_eq!(Some("HE"), s);}assert_eq!("HEllo", v);1.20.0 ·Sourcepub unsafe fnget_unchecked<I>(&self, i: I) -> &<I asSliceIndex<str>>::Outputwhere I:SliceIndex<str>,
pub unsafe fnget_unchecked<I>(&self, i: I) -> &<I asSliceIndex<str>>::Outputwhere I:SliceIndex<str>,
Returns an unchecked subslice ofstr.
This is the unchecked alternative to indexing thestr.
§Safety
Callers of this function are responsible that these preconditions aresatisfied:
- 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 orviolate the invariants communicated by thestr type.
§Examples
1.20.0 ·Sourcepub unsafe fnget_unchecked_mut<I>( &mut self, i: I,) -> &mut <I asSliceIndex<str>>::Outputwhere I:SliceIndex<str>,
pub unsafe fnget_unchecked_mut<I>( &mut self, i: I,) -> &mut <I asSliceIndex<str>>::Outputwhere I:SliceIndex<str>,
Returns a mutable, unchecked subslice ofstr.
This is the unchecked alternative to indexing thestr.
§Safety
Callers of this function are responsible that these preconditions aresatisfied:
- 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 orviolate the invariants communicated by thestr type.
§Examples
1.0.0 ·Sourcepub unsafe fnslice_unchecked(&self, begin:usize, end:usize) -> &str
👎Deprecated since 1.29.0: useget_unchecked(begin..end) instead
pub unsafe fnslice_unchecked(&self, begin:usize, end:usize) -> &str
get_unchecked(begin..end) insteadCreates a string slice from another string slice, bypassing safetychecks.
This is generally not recommended, use with caution! For a safealternative seestr andIndex.
This new slice goes frombegin toend, includingbegin butexcludingend.
To get a mutable string slice instead, see theslice_mut_unchecked method.
§Safety
Callers of this function are responsible that three preconditions aresatisfied:
beginmust not exceedend.beginandendmust be byte positions within the string slice.beginandendmust lie on UTF-8 sequence boundaries.
§Examples
1.5.0 ·Sourcepub unsafe fnslice_mut_unchecked( &mut self, begin:usize, end:usize,) -> &mutstr
👎Deprecated since 1.29.0: useget_unchecked_mut(begin..end) instead
pub unsafe fnslice_mut_unchecked( &mut self, begin:usize, end:usize,) -> &mutstr
get_unchecked_mut(begin..end) insteadCreates a string slice from another string slice, bypassing safetychecks.
This is generally not recommended, use with caution! For a safealternative seestr andIndexMut.
This new slice goes frombegin toend, includingbegin butexcludingend.
To get an immutable string slice instead, see theslice_unchecked method.
§Safety
Callers of this function are responsible that three preconditions aresatisfied:
beginmust not exceedend.beginandendmust be byte positions within the string slice.beginandendmust lie on UTF-8 sequence boundaries.
1.4.0 (const: 1.86.0) ·Sourcepub const fnsplit_at(&self, mid:usize) -> (&str, &str)
pub const fnsplit_at(&self, mid:usize) -> (&str, &str)
Divides one string slice into two at an index.
The argument,mid, should be a byte offset from the start of thestring. 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 tomid,and frommid to the end of the string slice.
To get mutable string slices instead, see thesplit_at_mutmethod.
§Panics
Panics ifmid is not on a UTF-8 code point boundary, or if it is pastthe end of the last code point of the string slice. For a non-panickingalternative seesplit_at_checked.
§Examples
1.4.0 (const: 1.86.0) ·Sourcepub const fnsplit_at_mut(&mut self, mid:usize) -> (&mutstr, &mutstr)
pub const fnsplit_at_mut(&mut self, mid:usize) -> (&mutstr, &mutstr)
Divides one mutable string slice into two at an index.
The argument,mid, should be a byte offset from the start of thestring. 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 tomid,and frommid to the end of the string slice.
To get immutable string slices instead, see thesplit_at method.
§Panics
Panics ifmid is not on a UTF-8 code point boundary, or if it is pastthe end of the last code point of the string slice. For a non-panickingalternative seesplit_at_mut_checked.
§Examples
1.80.0 (const: 1.86.0) ·Sourcepub const fnsplit_at_checked(&self, mid:usize) ->Option<(&str, &str)>
pub const fnsplit_at_checked(&self, mid:usize) ->Option<(&str, &str)>
Divides one string slice into two at an index.
The argument,mid, should be a valid byte offset from the start of thestring. It must also be on the boundary of a UTF-8 code point. Themethod returnsNone if that’s not the case.
The two slices returned go from the start of the string slice tomid,and frommid to the end of the string slice.
To get mutable string slices instead, see thesplit_at_mut_checkedmethod.
§Examples
1.80.0 (const: 1.86.0) ·Sourcepub const fnsplit_at_mut_checked( &mut self, mid:usize,) ->Option<(&mutstr, &mutstr)>
pub const fnsplit_at_mut_checked( &mut self, mid:usize,) ->Option<(&mutstr, &mutstr)>
Divides one mutable string slice into two at an index.
The argument,mid, should be a valid byte offset from the start of thestring. It must also be on the boundary of a UTF-8 code point. Themethod returnsNone if that’s not the case.
The two slices returned go from the start of the string slice tomid,and frommid to the end of the string slice.
To get immutable string slices instead, see thesplit_at_checked method.
§Examples
letmuts ="Per Martin-Löf".to_string();if letSome((first, last)) = s.split_at_mut_checked(3) { first.make_ascii_uppercase();assert_eq!("PER", first);assert_eq!(" Martin-Löf", last);}assert_eq!("PER Martin-Löf", s);assert_eq!(None, s.split_at_mut_checked(13));// Inside “ö”assert_eq!(None, s.split_at_mut_checked(16));// Beyond the string length1.0.0 ·Sourcepub fnchars(&self) ->Chars<'_>ⓘ
pub fnchars(&self) ->Chars<'_>ⓘ
Returns an iterator over thechars of a string slice.
As a string slice consists of valid UTF-8, we can iterate through astring slice bychar. This method returns such an iterator.
It’s important to remember thatchar represents a Unicode ScalarValue, and might not match your idea of what a ‘character’ is. Iterationover grapheme clusters may be what you actually want. This functionalityis not provided by Rust’s standard library, check crates.io instead.
§Examples
Basic usage:
letword ="goodbye";letcount = word.chars().count();assert_eq!(7, count);letmutchars = 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,chars might not match your intuition about characters:
1.0.0 ·Sourcepub fnchar_indices(&self) ->CharIndices<'_>ⓘ
pub fnchar_indices(&self) ->CharIndices<'_>ⓘ
Returns an iterator over thechars of a string slice, and theirpositions.
As a string slice consists of valid UTF-8, we can iterate through astring slice bychar. This method returns an iterator of boththesechars, as well as their byte positions.
The iterator yields tuples. The position is first, thechar issecond.
§Examples
Basic usage:
letword ="goodbye";letcount = word.char_indices().count();assert_eq!(7, count);letmutchar_indices = word.char_indices();assert_eq!(Some((0,'g')), char_indices.next());assert_eq!(Some((1,'o')), char_indices.next());assert_eq!(Some((2,'o')), char_indices.next());assert_eq!(Some((3,'d')), char_indices.next());assert_eq!(Some((4,'b')), char_indices.next());assert_eq!(Some((5,'y')), char_indices.next());assert_eq!(Some((6,'e')), char_indices.next());assert_eq!(None, char_indices.next());Remember,chars might not match your intuition about characters:
letyes ="y̆es";letmutchar_indices = yes.char_indices();assert_eq!(Some((0,'y')), char_indices.next());// not (0, 'y̆')assert_eq!(Some((1,'\u{0306}')), char_indices.next());// note the 3 here - the previous character took up two bytesassert_eq!(Some((3,'e')), char_indices.next());assert_eq!(Some((4,'s')), char_indices.next());assert_eq!(None, char_indices.next());1.0.0 ·Sourcepub fnbytes(&self) ->Bytes<'_>ⓘ
pub fnbytes(&self) ->Bytes<'_>ⓘ
Returns an iterator over the bytes of a string slice.
As a string slice consists of a sequence of bytes, we can iteratethrough a string slice by byte. This method returns such an iterator.
§Examples
1.1.0 ·Sourcepub fnsplit_whitespace(&self) ->SplitWhitespace<'_>ⓘ
pub fnsplit_whitespace(&self) ->SplitWhitespace<'_>ⓘ
Splits a string slice by whitespace.
The iterator returned will return string slices that are sub-slices ofthe original string slice, separated by any amount of whitespace.
‘Whitespace’ is defined according to the terms of the Unicode DerivedCore PropertyWhite_Space. If you only want to split on ASCII whitespaceinstead, usesplit_ascii_whitespace.
§Examples
Basic usage:
letmutiter ="A few words".split_whitespace();assert_eq!(Some("A"), iter.next());assert_eq!(Some("few"), iter.next());assert_eq!(Some("words"), iter.next());assert_eq!(None, iter.next());All kinds of whitespace are considered:
letmutiter =" Mary had\ta\u{2009}little \n\t lamb".split_whitespace();assert_eq!(Some("Mary"), iter.next());assert_eq!(Some("had"), iter.next());assert_eq!(Some("a"), iter.next());assert_eq!(Some("little"), iter.next());assert_eq!(Some("lamb"), iter.next());assert_eq!(None, iter.next());If the string is empty or all whitespace, the iterator yields no string slices:
1.34.0 ·Sourcepub fnsplit_ascii_whitespace(&self) ->SplitAsciiWhitespace<'_>ⓘ
pub fnsplit_ascii_whitespace(&self) ->SplitAsciiWhitespace<'_>ⓘ
Splits a string slice by ASCII whitespace.
The iterator returned will return string slices that are sub-slices ofthe original string slice, separated by any amount of ASCII whitespace.
This uses the same definition aschar::is_ascii_whitespace.To split by UnicodeWhitespace instead, usesplit_whitespace.
§Examples
Basic usage:
letmutiter ="A few words".split_ascii_whitespace();assert_eq!(Some("A"), iter.next());assert_eq!(Some("few"), iter.next());assert_eq!(Some("words"), iter.next());assert_eq!(None, iter.next());Various kinds of ASCII whitespace are considered(seechar::is_ascii_whitespace):
letmutiter =" Mary had\ta little \n\t lamb".split_ascii_whitespace();assert_eq!(Some("Mary"), iter.next());assert_eq!(Some("had"), iter.next());assert_eq!(Some("a"), iter.next());assert_eq!(Some("little"), iter.next());assert_eq!(Some("lamb"), iter.next());assert_eq!(None, iter.next());If the string is empty or all ASCII whitespace, the iterator yields no string slices:
1.0.0 ·Sourcepub fnlines(&self) ->Lines<'_>ⓘ
pub fnlines(&self) ->Lines<'_>ⓘ
Returns an iterator over the lines of a string, as string slices.
Lines are split at line endings that are either newlines (\n) orsequences of a carriage return followed by a line feed (\r\n).
Line terminators are not included in the lines returned by the iterator.
Note that any carriage return (\r) not immediately followed by aline feed (\n) does not split a line. These carriage returns arethereby included in the produced lines.
The final line ending is optional. A string that ends with a final lineending will return the same lines as an otherwise identical stringwithout a final line ending.
An empty string returns an empty iterator.
§Examples
Basic usage:
lettext ="foo\r\nbar\n\nbaz\r";letmutlines = text.lines();assert_eq!(Some("foo"), lines.next());assert_eq!(Some("bar"), lines.next());assert_eq!(Some(""), lines.next());// Trailing carriage return is included in the last lineassert_eq!(Some("baz\r"), lines.next());assert_eq!(None, lines.next());The final line does not require any ending:
lettext ="foo\nbar\n\r\nbaz";letmutlines = text.lines();assert_eq!(Some("foo"), lines.next());assert_eq!(Some("bar"), lines.next());assert_eq!(Some(""), lines.next());assert_eq!(Some("baz"), lines.next());assert_eq!(None, lines.next());An empty string returns an empty iterator:
1.0.0 ·Sourcepub fnlines_any(&self) ->LinesAny<'_>ⓘ
👎Deprecated since 1.4.0: use lines() instead now
pub fnlines_any(&self) ->LinesAny<'_>ⓘ
Returns an iterator over the lines of a string.
1.8.0 ·Sourcepub fnencode_utf16(&self) ->EncodeUtf16<'_>ⓘ
pub fnencode_utf16(&self) ->EncodeUtf16<'_>ⓘ
Returns an iterator ofu16 over the string encodedas native endian UTF-16 (without byte-order mark).
§Examples
1.0.0 ·Sourcepub fncontains<P>(&self, pat: P) ->boolwhere P:Pattern,
pub fncontains<P>(&self, pat: P) ->boolwhere P:Pattern,
1.0.0 ·Sourcepub fnstarts_with<P>(&self, pat: P) ->boolwhere P:Pattern,
pub fnstarts_with<P>(&self, pat: P) ->boolwhere P:Pattern,
Returnstrue if the given pattern matches a prefix of thisstring slice.
Returnsfalse if it does not.
Thepattern can be a&str, in which case this function will return true ifthe&str is a prefix of this string slice.
Thepattern can also be achar, a slice ofchars, or afunction or closure that determines if a character matches.These will only be checked against the first character of this string slice.Look at the second example below regarding behavior for slices ofchars.
§Examples
1.0.0 ·Sourcepub fnends_with<P>(&self, pat: P) ->bool
pub fnends_with<P>(&self, pat: P) ->bool
1.0.0 ·Sourcepub fnfind<P>(&self, pat: P) ->Option<usize>where P:Pattern,
pub fnfind<P>(&self, pat: P) ->Option<usize>where P:Pattern,
Returns the byte index of the first character of this string slice thatmatches the pattern.
ReturnsNone if the pattern doesn’t match.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
Simple patterns:
lets ="Löwe 老虎 Léopard Gepardi";assert_eq!(s.find('L'),Some(0));assert_eq!(s.find('é'),Some(14));assert_eq!(s.find("pard"),Some(17));More complex patterns using point-free style and closures:
lets ="Löwe 老虎 Léopard";assert_eq!(s.find(char::is_whitespace),Some(5));assert_eq!(s.find(char::is_lowercase),Some(1));assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()),Some(1));assert_eq!(s.find(|c: char| (c <'o') && (c >'a')),Some(4));Not finding the pattern:
1.0.0 ·Sourcepub fnrfind<P>(&self, pat: P) ->Option<usize>
pub fnrfind<P>(&self, pat: P) ->Option<usize>
Returns the byte index for the first character of the last match of the pattern inthis string slice.
ReturnsNone if the pattern doesn’t match.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
Simple patterns:
lets ="Löwe 老虎 Léopard Gepardi";assert_eq!(s.rfind('L'),Some(13));assert_eq!(s.rfind('é'),Some(14));assert_eq!(s.rfind("pard"),Some(24));More complex patterns with closures:
lets ="Löwe 老虎 Léopard";assert_eq!(s.rfind(char::is_whitespace),Some(12));assert_eq!(s.rfind(char::is_lowercase),Some(20));Not finding the pattern:
1.0.0 ·Sourcepub fnsplit<P>(&self, pat: P) ->Split<'_, P>ⓘwhere P:Pattern,
pub fnsplit<P>(&self, pat: P) ->Split<'_, P>ⓘwhere P:Pattern,
Returns an iterator over substrings of this string slice, separated bycharacters matched by a pattern.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
If there are no matches the full string slice is returned as the onlyitem in the iterator.
§Iterator behavior
The returned iterator will be aDoubleEndedIterator if the patternallows a reverse search and forward/reverse search yields the sameelements. This is true for, e.g.,char, but not for&str.
If the pattern allows a reverse search but its results might differfrom a forward search, thersplit method can be used.
§Examples
Simple patterns:
letv: Vec<&str> ="Mary had a little lamb".split(' ').collect();assert_eq!(v, ["Mary","had","a","little","lamb"]);letv: Vec<&str> ="".split('X').collect();assert_eq!(v, [""]);letv: Vec<&str> ="lionXXtigerXleopard".split('X').collect();assert_eq!(v, ["lion","","tiger","leopard"]);letv: Vec<&str> ="lion::tiger::leopard".split("::").collect();assert_eq!(v, ["lion","tiger","leopard"]);letv: Vec<&str> ="AABBCC".split("DD").collect();assert_eq!(v, ["AABBCC"]);letv: Vec<&str> ="abc1def2ghi".split(char::is_numeric).collect();assert_eq!(v, ["abc","def","ghi"]);letv: Vec<&str> ="lionXtigerXleopard".split(char::is_uppercase).collect();assert_eq!(v, ["lion","tiger","leopard"]);If the pattern is a slice of chars, split on each occurrence of any of the characters:
letv: Vec<&str> ="2020-11-03 23:59".split(&['-',' ',':','@'][..]).collect();assert_eq!(v, ["2020","11","03","23","59"]);A more complex pattern, using a closure:
letv: Vec<&str> ="abc1defXghi".split(|c| c =='1'|| c =='X').collect();assert_eq!(v, ["abc","def","ghi"]);If a string contains multiple contiguous separators, you will end upwith empty strings in the output:
letx ="||||a||b|c".to_string();letd: Vec<_> = x.split('|').collect();assert_eq!(d,&["","","","","a","","b","c"]);Contiguous separators are separated by the empty string.
Separators at the start or end of a string are neighboredby empty strings.
When the empty string is used as a separator, it separatesevery character in the string, along with the beginningand end of the string.
Contiguous separators can lead to possibly surprising behaviorwhen whitespace is used as the separator. This code is correct:
letx =" a b c".to_string();letd: Vec<_> = x.split(' ').collect();assert_eq!(d,&["","","","","a","","b","c"]);It doesnot give you:
Usesplit_whitespace for this behavior.
1.51.0 ·Sourcepub fnsplit_inclusive<P>(&self, pat: P) ->SplitInclusive<'_, P>ⓘwhere P:Pattern,
pub fnsplit_inclusive<P>(&self, pat: P) ->SplitInclusive<'_, P>ⓘwhere P:Pattern,
Returns an iterator over substrings of this string slice, separated bycharacters matched by a pattern.
Differs from the iterator produced bysplit in thatsplit_inclusiveleaves the matched part as the terminator of the substring.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
letv: Vec<&str> ="Mary had a little lamb\nlittle lamb\nlittle lamb.".split_inclusive('\n').collect();assert_eq!(v, ["Mary had a little lamb\n","little lamb\n","little lamb."]);If the last element of the string is matched,that element will be considered the terminator of the preceding substring.That substring will be the last item returned by the iterator.
1.0.0 ·Sourcepub fnrsplit<P>(&self, pat: P) ->RSplit<'_, P>ⓘ
pub fnrsplit<P>(&self, pat: P) ->RSplit<'_, P>ⓘ
Returns an iterator over substrings of the given string slice, separatedby characters matched by a pattern and yielded in reverse order.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator requires that the pattern supports a reversesearch, and it will be aDoubleEndedIterator if a forward/reversesearch yields the same elements.
For iterating from the front, thesplit method can be used.
§Examples
Simple patterns:
letv: Vec<&str> ="Mary had a little lamb".rsplit(' ').collect();assert_eq!(v, ["lamb","little","a","had","Mary"]);letv: Vec<&str> ="".rsplit('X').collect();assert_eq!(v, [""]);letv: Vec<&str> ="lionXXtigerXleopard".rsplit('X').collect();assert_eq!(v, ["leopard","tiger","","lion"]);letv: Vec<&str> ="lion::tiger::leopard".rsplit("::").collect();assert_eq!(v, ["leopard","tiger","lion"]);A more complex pattern, using a closure:
1.0.0 ·Sourcepub fnsplit_terminator<P>(&self, pat: P) ->SplitTerminator<'_, P>ⓘwhere P:Pattern,
pub fnsplit_terminator<P>(&self, pat: P) ->SplitTerminator<'_, P>ⓘwhere P:Pattern,
Returns an iterator over substrings of the given string slice, separatedby characters matched by a pattern.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
Equivalent tosplit, except that the trailing substringis skipped if empty.
This method can be used for string data that isterminated,rather thanseparated by a pattern.
§Iterator behavior
The returned iterator will be aDoubleEndedIterator if the patternallows a reverse search and forward/reverse search yields the sameelements. This is true for, e.g.,char, but not for&str.
If the pattern allows a reverse search but its results might differfrom a forward search, thersplit_terminator method can be used.
§Examples
1.0.0 ·Sourcepub fnrsplit_terminator<P>(&self, pat: P) ->RSplitTerminator<'_, P>ⓘ
pub fnrsplit_terminator<P>(&self, pat: P) ->RSplitTerminator<'_, P>ⓘ
Returns an iterator over substrings ofself, separated by charactersmatched by a pattern and yielded in reverse order.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
Equivalent tosplit, except that the trailing substring isskipped if empty.
This method can be used for string data that isterminated,rather thanseparated by a pattern.
§Iterator behavior
The returned iterator requires that the pattern supports areverse search, and it will be double ended if a forward/reversesearch yields the same elements.
For iterating from the front, thesplit_terminator method can beused.
§Examples
1.0.0 ·Sourcepub fnsplitn<P>(&self, n:usize, pat: P) ->SplitN<'_, P>ⓘwhere P:Pattern,
pub fnsplitn<P>(&self, n:usize, pat: P) ->SplitN<'_, P>ⓘwhere P:Pattern,
Returns an iterator over substrings of the given string slice, separatedby a pattern, restricted to returning at mostn items.
Ifn substrings are returned, the last substring (thenth substring)will contain the remainder of the string.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator will not be double ended, because it isnot efficient to support.
If the pattern allows a reverse search, thersplitn method can beused.
§Examples
Simple patterns:
letv: Vec<&str> ="Mary had a little lambda".splitn(3,' ').collect();assert_eq!(v, ["Mary","had","a little lambda"]);letv: Vec<&str> ="lionXXtigerXleopard".splitn(3,"X").collect();assert_eq!(v, ["lion","","tigerXleopard"]);letv: Vec<&str> ="abcXdef".splitn(1,'X').collect();assert_eq!(v, ["abcXdef"]);letv: Vec<&str> ="".splitn(1,'X').collect();assert_eq!(v, [""]);A more complex pattern, using a closure:
1.0.0 ·Sourcepub fnrsplitn<P>(&self, n:usize, pat: P) ->RSplitN<'_, P>ⓘ
pub fnrsplitn<P>(&self, n:usize, pat: P) ->RSplitN<'_, P>ⓘ
Returns an iterator over substrings of this string slice, separated by apattern, starting from the end of the string, restricted to returning atmostn items.
Ifn substrings are returned, the last substring (thenth substring)will contain the remainder of the string.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator will not be double ended, because it is notefficient to support.
For splitting from the front, thesplitn method can be used.
§Examples
Simple patterns:
letv: Vec<&str> ="Mary had a little lamb".rsplitn(3,' ').collect();assert_eq!(v, ["lamb","little","Mary had a"]);letv: Vec<&str> ="lionXXtigerXleopard".rsplitn(3,'X').collect();assert_eq!(v, ["leopard","tiger","lionX"]);letv: Vec<&str> ="lion::tiger::leopard".rsplitn(2,"::").collect();assert_eq!(v, ["leopard","lion::tiger"]);A more complex pattern, using a closure:
1.52.0 ·Sourcepub fnsplit_once<P>(&self, delimiter: P) ->Option<(&str, &str)>where P:Pattern,
pub fnsplit_once<P>(&self, delimiter: P) ->Option<(&str, &str)>where P:Pattern,
Splits the string on the first occurrence of the specified delimiter andreturns prefix before delimiter and suffix after delimiter.
§Examples
1.52.0 ·Sourcepub fnrsplit_once<P>(&self, delimiter: P) ->Option<(&str, &str)>
pub fnrsplit_once<P>(&self, delimiter: P) ->Option<(&str, &str)>
Splits the string on the last occurrence of the specified delimiter andreturns prefix before delimiter and suffix after delimiter.
§Examples
1.2.0 ·Sourcepub fnmatches<P>(&self, pat: P) ->Matches<'_, P>ⓘwhere P:Pattern,
pub fnmatches<P>(&self, pat: P) ->Matches<'_, P>ⓘwhere P:Pattern,
Returns an iterator over the disjoint matches of a pattern within thegiven string slice.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator will be aDoubleEndedIterator if the patternallows a reverse search and forward/reverse search yields the sameelements. This is true for, e.g.,char, but not for&str.
If the pattern allows a reverse search but its results might differfrom a forward search, thermatches method can be used.
§Examples
1.2.0 ·Sourcepub fnrmatches<P>(&self, pat: P) ->RMatches<'_, P>ⓘ
pub fnrmatches<P>(&self, pat: P) ->RMatches<'_, P>ⓘ
Returns an iterator over the disjoint matches of a pattern within thisstring slice, yielded in reverse order.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator requires that the pattern supports a reversesearch, and it will be aDoubleEndedIterator if a forward/reversesearch yields the same elements.
For iterating from the front, thematches method can be used.
§Examples
1.5.0 ·Sourcepub fnmatch_indices<P>(&self, pat: P) ->MatchIndices<'_, P>ⓘwhere P:Pattern,
pub fnmatch_indices<P>(&self, pat: P) ->MatchIndices<'_, P>ⓘwhere P:Pattern,
Returns an iterator over the disjoint matches of a pattern within this stringslice as well as the index that the match starts at.
For matches ofpat withinself that overlap, only the indicescorresponding to the first match are returned.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator will be aDoubleEndedIterator if the patternallows a reverse search and forward/reverse search yields the sameelements. This is true for, e.g.,char, but not for&str.
If the pattern allows a reverse search but its results might differfrom a forward search, thermatch_indices method can be used.
§Examples
letv: Vec<_> ="abcXXXabcYYYabc".match_indices("abc").collect();assert_eq!(v, [(0,"abc"), (6,"abc"), (12,"abc")]);letv: Vec<_> ="1abcabc2".match_indices("abc").collect();assert_eq!(v, [(1,"abc"), (4,"abc")]);letv: Vec<_> ="ababa".match_indices("aba").collect();assert_eq!(v, [(0,"aba")]);// only the first `aba`1.5.0 ·Sourcepub fnrmatch_indices<P>(&self, pat: P) ->RMatchIndices<'_, P>ⓘ
pub fnrmatch_indices<P>(&self, pat: P) ->RMatchIndices<'_, P>ⓘ
Returns an iterator over the disjoint matches of a pattern withinself,yielded in reverse order along with the index of the match.
For matches ofpat withinself that overlap, only the indicescorresponding to the last match are returned.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Iterator behavior
The returned iterator requires that the pattern supports a reversesearch, and it will be aDoubleEndedIterator if a forward/reversesearch yields the same elements.
For iterating from the front, thematch_indices method can be used.
§Examples
letv: Vec<_> ="abcXXXabcYYYabc".rmatch_indices("abc").collect();assert_eq!(v, [(12,"abc"), (6,"abc"), (0,"abc")]);letv: Vec<_> ="1abcabc2".rmatch_indices("abc").collect();assert_eq!(v, [(4,"abc"), (1,"abc")]);letv: Vec<_> ="ababa".rmatch_indices("aba").collect();assert_eq!(v, [(2,"aba")]);// only the last `aba`1.0.0 ·Sourcepub fntrim(&self) -> &str
pub fntrim(&self) -> &str
Returns a string slice with leading and trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode DerivedCore PropertyWhite_Space, which includes newlines.
§Examples
1.30.0 ·Sourcepub fntrim_start(&self) -> &str
pub fntrim_start(&self) -> &str
Returns a string slice with leading whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode DerivedCore PropertyWhite_Space, which includes newlines.
§Text directionality
A string is a sequence of bytes.start in this context means the firstposition of that byte string; for a left-to-right language like English orRussian, this will be left side, and for right-to-left languages likeArabic or Hebrew, this will be the right side.
§Examples
Basic usage:
Directionality:
1.30.0 ·Sourcepub fntrim_end(&self) -> &str
pub fntrim_end(&self) -> &str
Returns a string slice with trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode DerivedCore PropertyWhite_Space, which includes newlines.
§Text directionality
A string is a sequence of bytes.end in this context means the lastposition of that byte string; for a left-to-right language like English orRussian, this will be right side, and for right-to-left languages likeArabic or Hebrew, this will be the left side.
§Examples
Basic usage:
Directionality:
1.0.0 ·Sourcepub fntrim_left(&self) -> &str
👎Deprecated since 1.33.0: superseded bytrim_start
pub fntrim_left(&self) -> &str
trim_startReturns a string slice with leading whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode DerivedCore PropertyWhite_Space.
§Text directionality
A string is a sequence of bytes. ‘Left’ in this context means the firstposition of that byte string; for a language like Arabic or Hebrewwhich are ‘right to left’ rather than ‘left to right’, this will betheright side, not the left.
§Examples
Basic usage:
Directionality:
1.0.0 ·Sourcepub fntrim_right(&self) -> &str
👎Deprecated since 1.33.0: superseded bytrim_end
pub fntrim_right(&self) -> &str
trim_endReturns a string slice with trailing whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode DerivedCore PropertyWhite_Space.
§Text directionality
A string is a sequence of bytes. ‘Right’ in this context means the lastposition of that byte string; for a language like Arabic or Hebrewwhich are ‘right to left’ rather than ‘left to right’, this will betheleft side, not the right.
§Examples
Basic usage:
Directionality:
1.0.0 ·Sourcepub fntrim_matches<P>(&self, pat: P) -> &str
pub fntrim_matches<P>(&self, pat: P) -> &str
Returns a string slice with all prefixes and suffixes that match apattern repeatedly removed.
Thepattern can be achar, a slice ofchars, or a functionor closure that determines if a character matches.
§Examples
Simple patterns:
assert_eq!("11foo1bar11".trim_matches('1'),"foo1bar");assert_eq!("123foo1bar123".trim_matches(char::is_numeric),"foo1bar");letx:&[_] =&['1','2'];assert_eq!("12foo1bar12".trim_matches(x),"foo1bar");A more complex pattern, using a closure:
1.30.0 ·Sourcepub fntrim_start_matches<P>(&self, pat: P) -> &strwhere P:Pattern,
pub fntrim_start_matches<P>(&self, pat: P) -> &strwhere P:Pattern,
Returns a string slice with all prefixes that match a patternrepeatedly removed.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Text directionality
A string is a sequence of bytes.start in this context means the firstposition of that byte string; for a left-to-right language like English orRussian, this will be left side, and for right-to-left languages likeArabic or Hebrew, this will be the right side.
§Examples
1.45.0 ·Sourcepub fnstrip_prefix<P>(&self, prefix: P) ->Option<&str>where P:Pattern,
pub fnstrip_prefix<P>(&self, prefix: P) ->Option<&str>where P:Pattern,
Returns a string slice with the prefix removed.
If the string starts with the patternprefix, returns the substring after the prefix,wrapped inSome. Unliketrim_start_matches, this method removes the prefix exactly once.
If the string does not start withprefix, returnsNone.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
1.45.0 ·Sourcepub fnstrip_suffix<P>(&self, suffix: P) ->Option<&str>
pub fnstrip_suffix<P>(&self, suffix: P) ->Option<&str>
Returns a string slice with the suffix removed.
If the string ends with the patternsuffix, returns the substring before the suffix,wrapped inSome. Unliketrim_end_matches, this method removes the suffix exactly once.
If the string does not end withsuffix, returnsNone.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
Sourcepub fnstrip_circumfix<P, S>(&self, prefix: P, suffix: S) ->Option<&str>
🔬This is a nightly-only experimental API. (strip_circumfix #147946)
pub fnstrip_circumfix<P, S>(&self, prefix: P, suffix: S) ->Option<&str>
strip_circumfix #147946)Returns a string slice with the prefix and suffix removed.
If the string starts with the patternprefix and ends with the patternsuffix, returnsthe substring after the prefix and before the suffix, wrapped inSome.Unliketrim_start_matches andtrim_end_matches, this method removes both the prefixand suffix exactly once.
If the string does not start withprefix or does not end withsuffix, returnsNone.
Eachpattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
Sourcepub fntrim_prefix<P>(&self, prefix: P) -> &strwhere P:Pattern,
🔬This is a nightly-only experimental API. (trim_prefix_suffix #142312)
pub fntrim_prefix<P>(&self, prefix: P) -> &strwhere P:Pattern,
trim_prefix_suffix #142312)Returns a string slice with the optional prefix removed.
If the string starts with the patternprefix, returns the substring after the prefix.Unlikestrip_prefix, this method always returns&str for easy method chaining,instead of returningOption<&str>.
If the string does not start withprefix, returns the original string unchanged.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
#![feature(trim_prefix_suffix)]// Prefix present - removes itassert_eq!("foo:bar".trim_prefix("foo:"),"bar");assert_eq!("foofoo".trim_prefix("foo"),"foo");// Prefix absent - returns original stringassert_eq!("foo:bar".trim_prefix("bar"),"foo:bar");// Method chaining exampleassert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'),"https://example.com/");Sourcepub fntrim_suffix<P>(&self, suffix: P) -> &str
🔬This is a nightly-only experimental API. (trim_prefix_suffix #142312)
pub fntrim_suffix<P>(&self, suffix: P) -> &str
trim_prefix_suffix #142312)Returns a string slice with the optional suffix removed.
If the string ends with the patternsuffix, returns the substring before the suffix.Unlikestrip_suffix, this method always returns&str for easy method chaining,instead of returningOption<&str>.
If the string does not end withsuffix, returns the original string unchanged.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Examples
#![feature(trim_prefix_suffix)]// Suffix present - removes itassert_eq!("bar:foo".trim_suffix(":foo"),"bar");assert_eq!("foofoo".trim_suffix("foo"),"foo");// Suffix absent - returns original stringassert_eq!("bar:foo".trim_suffix("bar"),"bar:foo");// Method chaining exampleassert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'),"https://example.com/");1.30.0 ·Sourcepub fntrim_end_matches<P>(&self, pat: P) -> &str
pub fntrim_end_matches<P>(&self, pat: P) -> &str
Returns a string slice with all suffixes that match a patternrepeatedly removed.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Text directionality
A string is a sequence of bytes.end in this context means the lastposition of that byte string; for a left-to-right language like English orRussian, this will be right side, and for right-to-left languages likeArabic or Hebrew, this will be the left side.
§Examples
Simple patterns:
assert_eq!("11foo1bar11".trim_end_matches('1'),"11foo1bar");assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric),"123foo1bar");letx:&[_] =&['1','2'];assert_eq!("12foo1bar12".trim_end_matches(x),"12foo1bar");A more complex pattern, using a closure:
1.0.0 ·Sourcepub fntrim_left_matches<P>(&self, pat: P) -> &strwhere P:Pattern,
👎Deprecated since 1.33.0: superseded bytrim_start_matches
pub fntrim_left_matches<P>(&self, pat: P) -> &strwhere P:Pattern,
trim_start_matchesReturns a string slice with all prefixes that match a patternrepeatedly removed.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Text directionality
A string is a sequence of bytes. ‘Left’ in this context means the firstposition of that byte string; for a language like Arabic or Hebrewwhich are ‘right to left’ rather than ‘left to right’, this will betheright side, not the left.
§Examples
1.0.0 ·Sourcepub fntrim_right_matches<P>(&self, pat: P) -> &str
👎Deprecated since 1.33.0: superseded bytrim_end_matches
pub fntrim_right_matches<P>(&self, pat: P) -> &str
trim_end_matchesReturns a string slice with all suffixes that match a patternrepeatedly removed.
Thepattern can be a&str,char, a slice ofchars, or afunction or closure that determines if a character matches.
§Text directionality
A string is a sequence of bytes. ‘Right’ in this context means the lastposition of that byte string; for a language like Arabic or Hebrewwhich are ‘right to left’ rather than ‘left to right’, this will betheleft side, not the right.
§Examples
Simple patterns:
assert_eq!("11foo1bar11".trim_right_matches('1'),"11foo1bar");assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric),"123foo1bar");letx:&[_] =&['1','2'];assert_eq!("12foo1bar12".trim_right_matches(x),"12foo1bar");A more complex pattern, using a closure:
1.0.0 ·Sourcepub fnparse<F>(&self) ->Result<F, <F asFromStr>::Err>where F:FromStr,
pub fnparse<F>(&self) ->Result<F, <F asFromStr>::Err>where F:FromStr,
Parses this string slice into another type.
Becauseparse is so general, it can cause problems with typeinference. As such,parse is one of the few times you’ll seethe syntax affectionately known as the ‘turbofish’:::<>. Thishelps the inference algorithm understand specifically which typeyou’re trying to parse into.
parse can parse into any type that implements theFromStr trait.
§Errors
Will returnErr if it’s not possible to parse this string slice intothe desired type.
§Examples
Basic usage:
Using the ‘turbofish’ instead of annotatingfour:
Failing to parse:
1.23.0 (const: 1.74.0) ·Sourcepub const fnis_ascii(&self) ->bool
pub const fnis_ascii(&self) ->bool
Checks if all characters in this string are within the ASCII range.
An empty string returnstrue.
§Examples
Sourcepub const fnas_ascii(&self) ->Option<&[AsciiChar]>
🔬This is a nightly-only experimental API. (ascii_char #110998)
pub const fnas_ascii(&self) ->Option<&[AsciiChar]>
ascii_char #110998)If this string sliceis_ascii, returns it as a sliceofASCII characters, otherwise returnsNone.
Sourcepub const unsafe fnas_ascii_unchecked(&self) -> &[AsciiChar]
🔬This is a nightly-only experimental API. (ascii_char #110998)
pub const unsafe fnas_ascii_unchecked(&self) -> &[AsciiChar]
ascii_char #110998)Converts this string slice into a slice ofASCII characters,without checking whether they are valid.
§Safety
Every character in this string must be ASCII, or else this is UB.
1.23.0 (const: 1.89.0) ·Sourcepub const fneq_ignore_ascii_case(&self, other: &str) ->bool
pub const fneq_ignore_ascii_case(&self, other: &str) ->bool
Checks that two strings are an ASCII case-insensitive match.
Same asto_ascii_lowercase(a) == to_ascii_lowercase(b),but without allocating and copying temporaries.
§Examples
1.23.0 (const: 1.84.0) ·Sourcepub const fnmake_ascii_uppercase(&mut self)
pub const fnmake_ascii_uppercase(&mut self)
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, useto_ascii_uppercase().
§Examples
1.23.0 (const: 1.84.0) ·Sourcepub const fnmake_ascii_lowercase(&mut self)
pub const fnmake_ascii_lowercase(&mut self)
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, useto_ascii_lowercase().
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const fntrim_ascii_start(&self) -> &str
pub const fntrim_ascii_start(&self) -> &str
Returns a string slice with leading ASCII whitespace removed.
‘Whitespace’ refers to the definition used byu8::is_ascii_whitespace.
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const fntrim_ascii_end(&self) -> &str
pub const fntrim_ascii_end(&self) -> &str
Returns a string slice with trailing ASCII whitespace removed.
‘Whitespace’ refers to the definition used byu8::is_ascii_whitespace.
§Examples
1.80.0 (const: 1.80.0) ·Sourcepub const fntrim_ascii(&self) -> &str
pub const fntrim_ascii(&self) -> &str
Returns a string slice with leading and trailing ASCII whitespaceremoved.
‘Whitespace’ refers to the definition used byu8::is_ascii_whitespace.
§Examples
1.34.0 ·Sourcepub fnescape_debug(&self) ->EscapeDebug<'_>ⓘ
pub fnescape_debug(&self) ->EscapeDebug<'_>ⓘ
Returns an iterator that escapes each char inself withchar::escape_debug.
Note: only extended grapheme codepoints that begin the string will beescaped.
§Examples
As an iterator:
Usingprintln! directly:
Both are equivalent to:
Usingto_string:
1.34.0 ·Sourcepub fnescape_default(&self) ->EscapeDefault<'_>ⓘ
pub fnescape_default(&self) ->EscapeDefault<'_>ⓘ
Returns an iterator that escapes each char inself withchar::escape_default.
§Examples
As an iterator:
Usingprintln! directly:
Both are equivalent to:
Usingto_string:
1.34.0 ·Sourcepub fnescape_unicode(&self) ->EscapeUnicode<'_>ⓘ
pub fnescape_unicode(&self) ->EscapeUnicode<'_>ⓘ
Returns an iterator that escapes each char inself withchar::escape_unicode.
§Examples
As an iterator:
Usingprintln! directly:
Both are equivalent to:
Usingto_string:
Sourcepub fnsubstr_range(&self, substr: &str) ->Option<Range<usize>>
🔬This is a nightly-only experimental API. (substr_range #126769)
pub fnsubstr_range(&self, substr: &str) ->Option<Range<usize>>
substr_range #126769)Returns the range that a substring points to.
ReturnsNone ifsubstr does not point withinself.
Unlikestr::find,this does not search through the string.Instead, it uses pointer arithmetic to find where in the stringsubstr is derived from.
This is useful for extendingstr::split and similar methods.
Note that this method may return false positives (typically eitherSome(0..0) orSome(self.len()..self.len())) ifsubstr is azero-lengthstr that points at the beginning or end of another,independent,str.
§Examples
Sourcepub const fnas_str(&self) -> &str
🔬This is a nightly-only experimental API. (str_as_str #130366)
pub const fnas_str(&self) -> &str
str_as_str #130366)Returns the same string as a string slice&str.
This method is redundant when used directly on&str, butit helps dereferencing other string-like types to string slices,for example references toBox<str> orArc<str>.
Source§implstr
Methods for string slices.
implstr
Methods for string slices.
1.20.0 ·Sourcepub fninto_boxed_bytes(self:Box<str>) ->Box<[u8]>
pub fninto_boxed_bytes(self:Box<str>) ->Box<[u8]>
Converts aBox<str> into aBox<[u8]> without copying or allocating.
§Examples
1.0.0 ·Sourcepub fnreplace<P>(&self, from: P, to: &str) ->Stringwhere P:Pattern,
pub fnreplace<P>(&self, from: P, to: &str) ->Stringwhere P:Pattern,
Replaces all matches of a pattern with another string.
replace creates a newString, 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, itreplaces them with the replacement string slice.
§Examples
lets ="this is old";assert_eq!("this is new", s.replace("old","new"));assert_eq!("than an old", s.replace("is","an"));When the pattern doesn’t match, it returns this string slice asString:
1.16.0 ·Sourcepub fnreplacen<P>(&self, pat: P, to: &str, count:usize) ->Stringwhere P:Pattern,
pub fnreplacen<P>(&self, pat: P, to: &str, count:usize) ->Stringwhere P:Pattern,
Replaces first N matches of a pattern with another string.
replacen creates a newString, 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, itreplaces them with the replacement string slice at mostcount times.
§Examples
lets ="foo foo 123 foo";assert_eq!("new new 123 foo", s.replacen("foo","new",2));assert_eq!("faa fao 123 foo", s.replacen('o',"a",3));assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric,"new",1));When the pattern doesn’t match, it returns this string slice asString:
1.2.0 ·Sourcepub fnto_lowercase(&self) ->String
pub fnto_lowercase(&self) ->String
Returns the lowercase equivalent of this string slice, as a newString.
‘Lowercase’ is defined according to the terms of the Unicode Derived Core PropertyLowercase.
Since some characters can expand into multiple characters when changingthe case, this function returns aString instead of modifying theparameter in-place.
§Examples
Basic usage:
A tricky example, with sigma:
letsigma ="Σ";assert_eq!("σ", sigma.to_lowercase());// but at the end of a word, it's ς, not σ:letodysseus ="ὈΔΥΣΣΕΎΣ";assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());Languages without case are not changed:
1.2.0 ·Sourcepub fnto_uppercase(&self) ->String
pub fnto_uppercase(&self) ->String
Returns the uppercase equivalent of this string slice, as a newString.
‘Uppercase’ is defined according to the terms of the Unicode Derived Core PropertyUppercase.
Since some characters can expand into multiple characters when changingthe case, this function returns aString instead of modifying theparameter in-place.
§Examples
Basic usage:
Scripts without case are not changed:
One character can become multiple:
1.4.0 ·Sourcepub fninto_string(self:Box<str>) ->String
pub fninto_string(self:Box<str>) ->String
1.23.0 ·Sourcepub fnto_ascii_uppercase(&self) ->String
pub fnto_ascii_uppercase(&self) ->String
Returns a copy of this string where each character is mapped to itsASCII upper case equivalent.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’,but non-ASCII letters are unchanged.
To uppercase the value in-place, usemake_ascii_uppercase.
To uppercase ASCII characters in addition to non-ASCII characters, useto_uppercase.
§Examples
1.23.0 ·Sourcepub fnto_ascii_lowercase(&self) ->String
pub fnto_ascii_lowercase(&self) ->String
Returns a copy of this string where each character is mapped to itsASCII lower case equivalent.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’,but non-ASCII letters are unchanged.
To lowercase the value in-place, usemake_ascii_lowercase.
To lowercase ASCII characters in addition to non-ASCII characters, useto_lowercase.
§Examples
Trait Implementations§
1.0.0 ·Source§implAdd<&str> forString
Implements the+ operator for concatenating two strings.
implAdd<&str> forString
Implements the+ operator for concatenating two strings.
This consumes theString on the left-hand side and re-uses its buffer (growing it ifnecessary). This is done to avoid allocating a newString and copying the entire contents onevery operation, which would lead toO(n^2) running time when building ann-byte string byrepeated concatenation.
The string on the right-hand side is only borrowed; its contents are copied into the returnedString.
§Examples
Concatenating twoStrings takes the first by value and borrows the second:
leta = String::from("hello");letb = String::from(" world");letc = a +&b;// `a` is moved and can no longer be used here.If you want to keep using the firstString, you can clone it and append to the clone instead:
leta = String::from("hello");letb = String::from(" world");letc = a.clone() +&b;// `a` is still valid here.Concatenating&str slices can be done by converting the first to aString:
1.14.0 ·Source§impl<'a>AddAssign<&'astr> forCow<'a,str>
impl<'a>AddAssign<&'astr> forCow<'a,str>
Source§fnadd_assign(&mut self, rhs: &'astr)
fnadd_assign(&mut self, rhs: &'astr)
+= operation.Read more1.12.0 ·Source§implAddAssign<&str> forString
Implements the+= operator for appending to aString.
implAddAssign<&str> forString
Implements the+= operator for appending to aString.
This has the same behavior as thepush_str method.
Source§fnadd_assign(&mut self, other: &str)
fnadd_assign(&mut self, other: &str)
+= operation.Read more1.0.0 ·Source§implAsciiExt forstr
implAsciiExt forstr
Source§typeOwned =String
typeOwned =String
Source§fnis_ascii(&self) ->bool
fnis_ascii(&self) ->bool
Source§fnto_ascii_uppercase(&self) -> Self::Owned
fnto_ascii_uppercase(&self) -> Self::Owned
Source§fnto_ascii_lowercase(&self) -> Self::Owned
fnto_ascii_lowercase(&self) -> Self::Owned
Source§fneq_ignore_ascii_case(&self, o: &Self) ->bool
fneq_ignore_ascii_case(&self, o: &Self) ->bool
Source§fnmake_ascii_uppercase(&mut self)
fnmake_ascii_uppercase(&mut self)
Source§fnmake_ascii_lowercase(&mut self)
fnmake_ascii_lowercase(&mut self)
1.36.0 ·Source§implBorrowMut<str> forString
implBorrowMut<str> forString
Source§fnborrow_mut(&mut self) -> &mutstr
fnborrow_mut(&mut self) -> &mutstr
Source§implCloneToUninit forstr
implCloneToUninit forstr
Source§impl<S>Concat<str> for[S]
Note:str inConcat<str> is not meaningful here.This type parameter of the trait only exists to enable another impl.
impl<S>Concat<str> for[S]
Note:str inConcat<str> is not meaningful here.This type parameter of the trait only exists to enable another impl.
1.0.0 ·Source§impl<'a>Extend<&'astr> forString
impl<'a>Extend<&'astr> forString
1.0.0 ·Source§impl<'a>From<&str> forBox<dynError +Send +Sync + 'a>
impl<'a>From<&str> forBox<dynError +Send +Sync + 'a>
1.45.0 ·Source§implFrom<Cow<'_,str>> forBox<str>
implFrom<Cow<'_,str>> forBox<str>
Source§fnfrom(cow:Cow<'_,str>) ->Box<str>
fnfrom(cow:Cow<'_,str>) ->Box<str>
Converts aCow<'_, str> into aBox<str>
Whencow is theCow::Borrowed variant, thisconversion allocates on the heap and copies theunderlyingstr. Otherwise, it will try to reuse the ownedString’s allocation.
§Examples
Source§impl<'a>FromIterator<&'astr> forByteString
impl<'a>FromIterator<&'astr> forByteString
Source§fnfrom_iter<T>(iter: T) ->ByteStringwhere T:IntoIterator<Item = &'astr>,
fnfrom_iter<T>(iter: T) ->ByteStringwhere T:IntoIterator<Item = &'astr>,
1.0.0 ·Source§impl<'a>FromIterator<&'astr> forString
impl<'a>FromIterator<&'astr> forString
1.0.0 ·Source§implOrd forstr
Implements ordering of strings.
implOrd forstr
Implements ordering of strings.
Strings are orderedlexicographically by their byte values. This orders Unicode codepoints based on their positions in the code charts. This is not necessarily the same as“alphabetical” order, which varies by language and locale. Sorting strings according toculturally-accepted standards requires locale-specific data that is outside the scope ofthestr type.
Source§impl<'a>PartialEq<&str> forByteString
impl<'a>PartialEq<&str> forByteString
Source§impl<'a>PartialEq<ByteString> for &str
impl<'a>PartialEq<ByteString> for &str
Source§impl<'a>PartialEq<ByteString> forstr
impl<'a>PartialEq<ByteString> forstr
Source§impl<'a>PartialEq<str> forByteString
impl<'a>PartialEq<str> forByteString
1.0.0 ·Source§implPartialOrd<str> forOsStr
implPartialOrd<str> forOsStr
1.0.0 ·Source§implPartialOrd<str> forOsString
implPartialOrd<str> forOsString
1.0.0 ·Source§implPartialOrd forstr
Implements comparison operations on strings.
implPartialOrd forstr
Implements comparison operations on strings.
Strings are comparedlexicographically by their byte values. This compares Unicode codepoints based on their positions in the code charts. This is not necessarily the same as“alphabetical” order, which varies by language and locale. Comparing strings according toculturally-accepted standards requires locale-specific data that is outside the scope ofthestr type.
Source§impl<'b>Pattern for &'bstr
Non-allocating substring search.
impl<'b>Pattern for &'bstr
Non-allocating substring search.
Will handle the pattern"" as returning empty matches at each characterboundary.
§Examples
Source§fnis_prefix_of(self, haystack: &str) ->bool
🔬This is a nightly-only experimental API. (pattern #27721)
fnis_prefix_of(self, haystack: &str) ->bool
pattern #27721)Checks whether the pattern matches at the front of the haystack.
Source§fnis_contained_in(self, haystack: &str) ->bool
🔬This is a nightly-only experimental API. (pattern #27721)
fnis_contained_in(self, haystack: &str) ->bool
pattern #27721)Checks whether the pattern matches anywhere in the haystack
Source§fnstrip_prefix_of(self, haystack: &str) ->Option<&str>
🔬This is a nightly-only experimental API. (pattern #27721)
fnstrip_prefix_of(self, haystack: &str) ->Option<&str>
pattern #27721)Removes the pattern from the front of haystack, if it matches.
Source§fnis_suffix_of<'a>(self, haystack: &'astr) ->bool
🔬This is a nightly-only experimental API. (pattern #27721)
fnis_suffix_of<'a>(self, haystack: &'astr) ->bool
pattern #27721)Checks whether the pattern matches at the back of the haystack.
Source§fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>
🔬This is a nightly-only experimental API. (pattern #27721)
fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>
pattern #27721)Removes the pattern from the back of haystack, if it matches.
Source§typeSearcher<'a> =StrSearcher<'a, 'b>
typeSearcher<'a> =StrSearcher<'a, 'b>
pattern #27721)Source§fninto_searcher(self, haystack: &str) ->StrSearcher<'_, 'b>
fninto_searcher(self, haystack: &str) ->StrSearcher<'_, 'b>
pattern #27721)self and thehaystack to search in.Source§fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>
fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>
pattern #27721)1.73.0 ·Source§implSliceIndex<str> for (Bound<usize>,Bound<usize>)
Implements substring slicing for arbitrary bounds.
implSliceIndex<str> for (Bound<usize>,Bound<usize>)
Implements substring slicing for arbitrary bounds.
Returns a slice of the given string bounded by the byte indicesprovided by each bound.
This operation isO(1).
§Panics
Panics ifbegin orend (if it exists and once adjusted forinclusion/exclusion) does not point to the starting byte offset ofa character (as defined byis_char_boundary), ifbegin > end, or ifend > len.
Source§fnget(self, slice: &str) ->Option<&str>
fnget(self, slice: &str) ->Option<&str>
slice_index_methods)Source§fnget_mut(self, slice: &mutstr) ->Option<&mutstr>
fnget_mut(self, slice: &mutstr) ->Option<&mutstr>
slice_index_methods)Source§unsafe fnget_unchecked(self, slice:*conststr) ->*conststr
unsafe fnget_unchecked(self, slice:*conststr) ->*conststr
slice_index_methods)Source§unsafe fnget_unchecked_mut(self, slice:*mutstr) ->*mutstr
unsafe fnget_unchecked_mut(self, slice:*mutstr) ->*mutstr
slice_index_methods)1.20.0 (const:unstable) ·Source§implSliceIndex<str> forRange<usize>
Implements substring slicing with syntax&self[begin .. end] or&mut self[begin .. end].
implSliceIndex<str> forRange<usize>
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 isO(1).
Prior to 1.20.0, these indexing operations were still supported bydirect implementation ofIndex andIndexMut.
§Panics
Panics ifbegin orend does not point to the starting byte offset ofa character (as defined byis_char_boundary), ifbegin > end, or ifend > len.
§Examples
Source§fnget(self, slice: &str) ->Option<&<Range<usize> asSliceIndex<str>>::Output>
fnget(self, slice: &str) ->Option<&<Range<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <Range<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <Range<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<Range<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<Range<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<Range<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<Range<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§implSliceIndex<str> forRange<usize>
implSliceIndex<str> forRange<usize>
Source§fnget(self, slice: &str) ->Option<&<Range<usize> asSliceIndex<str>>::Output>
fnget(self, slice: &str) ->Option<&<Range<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <Range<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <Range<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<Range<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<Range<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<Range<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<Range<usize> asSliceIndex<str>>::Output
slice_index_methods)1.20.0 (const:unstable) ·Source§implSliceIndex<str> forRangeFrom<usize>
Implements substring slicing with syntax&self[begin ..] or&mut self[begin ..].
implSliceIndex<str> forRangeFrom<usize>
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 isO(1).
Prior to 1.20.0, these indexing operations were still supported bydirect implementation ofIndex andIndexMut.
§Panics
Panics ifbegin does not point to the starting byte offset ofa character (as defined byis_char_boundary), or ifbegin > len.
Source§fnget( self, slice: &str,) ->Option<&<RangeFrom<usize> asSliceIndex<str>>::Output>
fnget( self, slice: &str,) ->Option<&<RangeFrom<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeFrom<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeFrom<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeFrom<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeFrom<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeFrom<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeFrom<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§implSliceIndex<str> forRangeFrom<usize>
implSliceIndex<str> forRangeFrom<usize>
Source§fnget( self, slice: &str,) ->Option<&<RangeFrom<usize> asSliceIndex<str>>::Output>
fnget( self, slice: &str,) ->Option<&<RangeFrom<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeFrom<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeFrom<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeFrom<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeFrom<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeFrom<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeFrom<usize> asSliceIndex<str>>::Output
slice_index_methods)1.20.0 (const:unstable) ·Source§implSliceIndex<str> forRangeFull
Implements substring slicing with syntax&self[..] or&mut self[..].
implSliceIndex<str> forRangeFull
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]. Unlikeother indexing operations, this can never panic.
This operation isO(1).
Prior to 1.20.0, these indexing operations were still supported bydirect implementation ofIndex andIndexMut.
Equivalent to&self[0 .. len] or&mut self[0 .. len].
Source§fnget(self, slice: &str) ->Option<&<RangeFull asSliceIndex<str>>::Output>
fnget(self, slice: &str) ->Option<&<RangeFull asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeFull asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeFull asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeFull asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeFull asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeFull asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeFull asSliceIndex<str>>::Output
slice_index_methods)1.26.0 (const:unstable) ·Source§implSliceIndex<str> forRangeInclusive<usize>
Implements substring slicing with syntax&self[begin ..= end] or&mut self[begin ..= end].
implSliceIndex<str> forRangeInclusive<usize>
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]. Equivalent to&self [begin .. end + 1] or&mut self[begin .. end + 1], except ifend has the maximum value forusize.
This operation isO(1).
§Panics
Panics ifbegin does not point to the starting byte offset ofa character (as defined byis_char_boundary), ifend does not pointto the ending byte offset of a character (end + 1 is either a startingbyte offset or equal tolen), ifbegin > end, or ifend >= len.
Source§fnget( self, slice: &str,) ->Option<&<RangeInclusive<usize> asSliceIndex<str>>::Output>
fnget( self, slice: &str,) ->Option<&<RangeInclusive<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeInclusive<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeInclusive<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeInclusive<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeInclusive<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§fnindex( self, slice: &str,) -> &<RangeInclusive<usize> asSliceIndex<str>>::Outputⓘ
fnindex( self, slice: &str,) -> &<RangeInclusive<usize> asSliceIndex<str>>::Outputⓘ
slice_index_methods)Source§fnindex_mut( self, slice: &mutstr,) -> &mut <RangeInclusive<usize> asSliceIndex<str>>::Outputⓘ
fnindex_mut( self, slice: &mutstr,) -> &mut <RangeInclusive<usize> asSliceIndex<str>>::Outputⓘ
slice_index_methods)Source§implSliceIndex<str> forRangeInclusive<usize>
implSliceIndex<str> forRangeInclusive<usize>
Source§fnget( self, slice: &str,) ->Option<&<RangeInclusive<usize> asSliceIndex<str>>::Output>
fnget( self, slice: &str,) ->Option<&<RangeInclusive<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeInclusive<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeInclusive<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeInclusive<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeInclusive<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§fnindex( self, slice: &str,) -> &<RangeInclusive<usize> asSliceIndex<str>>::Output
fnindex( self, slice: &str,) -> &<RangeInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§fnindex_mut( self, slice: &mutstr,) -> &mut <RangeInclusive<usize> asSliceIndex<str>>::Output
fnindex_mut( self, slice: &mutstr,) -> &mut <RangeInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)1.20.0 (const:unstable) ·Source§implSliceIndex<str> forRangeTo<usize>
Implements substring slicing with syntax&self[.. end] or&mut self[.. end].
implSliceIndex<str> forRangeTo<usize>
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 isO(1).
Prior to 1.20.0, these indexing operations were still supported bydirect implementation ofIndex andIndexMut.
§Panics
Panics ifend does not point to the starting byte offset of acharacter (as defined byis_char_boundary), or ifend > len.
Source§fnget( self, slice: &str,) ->Option<&<RangeTo<usize> asSliceIndex<str>>::Output>
fnget( self, slice: &str,) ->Option<&<RangeTo<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeTo<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeTo<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeTo<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeTo<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeTo<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeTo<usize> asSliceIndex<str>>::Output
slice_index_methods)1.26.0 (const:unstable) ·Source§implSliceIndex<str> forRangeToInclusive<usize>
Implements substring slicing with syntax&self[..= end] or&mut self[..= end].
implSliceIndex<str> forRangeToInclusive<usize>
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 ifend has the maximumvalue forusize.
This operation isO(1).
§Panics
Panics ifend does not point to the ending byte offset of a character(end + 1 is either a starting byte offset as defined byis_char_boundary, or equal tolen), or ifend >= len.
Source§fnget( self, slice: &str,) ->Option<&<RangeToInclusive<usize> asSliceIndex<str>>::Output>
fnget( self, slice: &str,) ->Option<&<RangeToInclusive<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeToInclusive<usize> asSliceIndex<str>>::Output>
fnget_mut( self, slice: &mutstr,) ->Option<&mut <RangeToInclusive<usize> asSliceIndex<str>>::Output>
slice_index_methods)Source§unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeToInclusive<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked( self, slice:*conststr,) ->*const<RangeToInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeToInclusive<usize> asSliceIndex<str>>::Output
unsafe fnget_unchecked_mut( self, slice:*mutstr,) ->*mut<RangeToInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§fnindex( self, slice: &str,) -> &<RangeToInclusive<usize> asSliceIndex<str>>::Output
fnindex( self, slice: &str,) -> &<RangeToInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)Source§fnindex_mut( self, slice: &mutstr,) -> &mut <RangeToInclusive<usize> asSliceIndex<str>>::Output
fnindex_mut( self, slice: &mutstr,) -> &mut <RangeToInclusive<usize> asSliceIndex<str>>::Output
slice_index_methods)1.0.0 ·Source§implToSocketAddrs forstr
implToSocketAddrs forstr
Source§typeIter =IntoIter<SocketAddr>
typeIter =IntoIter<SocketAddr>
Source§fnto_socket_addrs(&self) ->Result<IntoIter<SocketAddr>>
fnto_socket_addrs(&self) ->Result<IntoIter<SocketAddr>>
SocketAddrs.Read more