1 //! String manipulation.
3 //! For more details, see the [`std::str`] module.
5 //! [`std::str`]: ../../std/str/index.html
7 #![stable(feature = "rust1", since = "1.0.0")]
15 use self::pattern::Pattern;
16 use self::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher};
20 use crate::slice::{self, SliceIndex};
24 #[unstable(feature = "str_internals", issue = "none")]
25 #[allow(missing_docs)]
28 #[stable(feature = "rust1", since = "1.0.0")]
29 pub use converts::{from_utf8, from_utf8_unchecked};
31 #[stable(feature = "str_mut_extras", since = "1.20.0")]
32 pub use converts::{from_utf8_mut, from_utf8_unchecked_mut};
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub use error::{ParseBoolError, Utf8Error};
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub use traits::FromStr;
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace};
43 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use iter::LinesAny;
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator};
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub use iter::{RSplitN, SplitN};
53 #[stable(feature = "str_matches", since = "1.2.0")]
54 pub use iter::{Matches, RMatches};
56 #[stable(feature = "str_match_indices", since = "1.5.0")]
57 pub use iter::{MatchIndices, RMatchIndices};
59 #[stable(feature = "encode_utf16", since = "1.8.0")]
60 pub use iter::EncodeUtf16;
62 #[stable(feature = "str_escape", since = "1.34.0")]
63 pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode};
65 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
66 pub use iter::SplitAsciiWhitespace;
68 #[unstable(feature = "split_inclusive", issue = "72360")]
69 use iter::SplitInclusive;
71 #[unstable(feature = "str_internals", issue = "none")]
72 pub use validations::next_code_point;
74 use iter::MatchIndicesInternal;
75 use iter::SplitInternal;
76 use iter::{MatchesInternal, SplitNInternal};
78 use validations::truncate_to_char_boundary;
83 fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
84 const MAX_DISPLAY_LENGTH: usize = 256;
85 let (truncated, s_trunc) = truncate_to_char_boundary(s, MAX_DISPLAY_LENGTH);
86 let ellipsis = if truncated { "[...]" } else { "" };
89 if begin > s.len() || end > s.len() {
90 let oob_index = if begin > s.len() { begin } else { end };
91 panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
97 "begin <= end ({} <= {}) when slicing `{}`{}",
104 // 3. character boundary
105 let index = if !s.is_char_boundary(begin) { begin } else { end };
106 // find the character
107 let mut char_start = index;
108 while !s.is_char_boundary(char_start) {
111 // `char_start` must be less than len and a char boundary
112 let ch = s[char_start..].chars().next().unwrap();
113 let char_range = char_start..char_start + ch.len_utf8();
115 "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
116 index, ch, char_range, s_trunc, ellipsis
123 /// Returns the length of `self`.
125 /// This length is in bytes, not [`char`]s or graphemes. In other words,
126 /// it may not be what a human considers the length of the string.
128 /// [`char`]: prim@char
135 /// let len = "foo".len();
136 /// assert_eq!(3, len);
138 /// assert_eq!("ƒoo".len(), 4); // fancy f!
139 /// assert_eq!("ƒoo".chars().count(), 3);
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_const_stable(feature = "const_str_len", since = "1.32.0")]
144 pub const fn len(&self) -> usize {
145 self.as_bytes().len()
148 /// Returns `true` if `self` has a length of zero bytes.
156 /// assert!(s.is_empty());
158 /// let s = "not empty";
159 /// assert!(!s.is_empty());
162 #[stable(feature = "rust1", since = "1.0.0")]
163 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.32.0")]
164 pub const fn is_empty(&self) -> bool {
168 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
169 /// sequence or the end of the string.
171 /// The start and end of the string (when `index == self.len()`) are
172 /// considered to be boundaries.
174 /// Returns `false` if `index` is greater than `self.len()`.
179 /// let s = "Löwe 老虎 Léopard";
180 /// assert!(s.is_char_boundary(0));
182 /// assert!(s.is_char_boundary(6));
183 /// assert!(s.is_char_boundary(s.len()));
185 /// // second byte of `ö`
186 /// assert!(!s.is_char_boundary(2));
188 /// // third byte of `老`
189 /// assert!(!s.is_char_boundary(8));
191 #[stable(feature = "is_char_boundary", since = "1.9.0")]
193 pub fn is_char_boundary(&self, index: usize) -> bool {
194 // 0 and len are always ok.
195 // Test for 0 explicitly so that it can optimize out the check
196 // easily and skip reading string data for that case.
197 if index == 0 || index == self.len() {
200 match self.as_bytes().get(index) {
202 // This is bit magic equivalent to: b < 128 || b >= 192
203 Some(&b) => (b as i8) >= -0x40,
207 /// Converts a string slice to a byte slice. To convert the byte slice back
208 /// into a string slice, use the [`from_utf8`] function.
215 /// let bytes = "bors".as_bytes();
216 /// assert_eq!(b"bors", bytes);
218 #[stable(feature = "rust1", since = "1.0.0")]
219 #[rustc_const_stable(feature = "str_as_bytes", since = "1.32.0")]
221 #[allow(unused_attributes)]
222 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
223 pub const fn as_bytes(&self) -> &[u8] {
224 // SAFETY: const sound because we transmute two types with the same layout
225 unsafe { mem::transmute(self) }
228 /// Converts a mutable string slice to a mutable byte slice.
232 /// The caller must ensure that the content of the slice is valid UTF-8
233 /// before the borrow ends and the underlying `str` is used.
235 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
242 /// let mut s = String::from("Hello");
243 /// let bytes = unsafe { s.as_bytes_mut() };
245 /// assert_eq!(b"Hello", bytes);
251 /// let mut s = String::from("🗻∈🌏");
254 /// let bytes = s.as_bytes_mut();
262 /// assert_eq!("🍔∈🌏", s);
264 #[stable(feature = "str_mut_extras", since = "1.20.0")]
266 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
267 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
268 // has the same layout as `&[u8]` (only libstd can make this guarantee).
269 // The pointer dereference is safe since it comes from a mutable reference which
270 // is guaranteed to be valid for writes.
271 unsafe { &mut *(self as *mut str as *mut [u8]) }
274 /// Converts a string slice to a raw pointer.
276 /// As string slices are a slice of bytes, the raw pointer points to a
277 /// [`u8`]. This pointer will be pointing to the first byte of the string
280 /// The caller must ensure that the returned pointer is never written to.
281 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
283 /// [`as_mut_ptr`]: str::as_mut_ptr
291 /// let ptr = s.as_ptr();
293 #[stable(feature = "rust1", since = "1.0.0")]
294 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
296 pub const fn as_ptr(&self) -> *const u8 {
297 self as *const str as *const u8
300 /// Converts a mutable string slice to a raw pointer.
302 /// As string slices are a slice of bytes, the raw pointer points to a
303 /// [`u8`]. This pointer will be pointing to the first byte of the string
306 /// It is your responsibility to make sure that the string slice only gets
307 /// modified in a way that it remains valid UTF-8.
308 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
310 pub fn as_mut_ptr(&mut self) -> *mut u8 {
311 self as *mut str as *mut u8
314 /// Returns a subslice of `str`.
316 /// This is the non-panicking alternative to indexing the `str`. Returns
317 /// [`None`] whenever equivalent indexing operation would panic.
322 /// let v = String::from("🗻∈🌏");
324 /// assert_eq!(Some("🗻"), v.get(0..4));
326 /// // indices not on UTF-8 sequence boundaries
327 /// assert!(v.get(1..).is_none());
328 /// assert!(v.get(..8).is_none());
331 /// assert!(v.get(..42).is_none());
333 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
335 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
339 /// Returns a mutable subslice of `str`.
341 /// This is the non-panicking alternative to indexing the `str`. Returns
342 /// [`None`] whenever equivalent indexing operation would panic.
347 /// let mut v = String::from("hello");
348 /// // correct length
349 /// assert!(v.get_mut(0..5).is_some());
351 /// assert!(v.get_mut(..42).is_none());
352 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
354 /// assert_eq!("hello", v);
356 /// let s = v.get_mut(0..2);
357 /// let s = s.map(|s| {
358 /// s.make_ascii_uppercase();
361 /// assert_eq!(Some("HE"), s);
363 /// assert_eq!("HEllo", v);
365 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
367 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
371 /// Returns an unchecked subslice of `str`.
373 /// This is the unchecked alternative to indexing the `str`.
377 /// Callers of this function are responsible that these preconditions are
380 /// * The starting index must not exceed the ending index;
381 /// * Indexes must be within bounds of the original slice;
382 /// * Indexes must lie on UTF-8 sequence boundaries.
384 /// Failing that, the returned string slice may reference invalid memory or
385 /// violate the invariants communicated by the `str` type.
392 /// assert_eq!("🗻", v.get_unchecked(0..4));
393 /// assert_eq!("∈", v.get_unchecked(4..7));
394 /// assert_eq!("🌏", v.get_unchecked(7..11));
397 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
399 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
400 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
401 // the slice is dereferencable because `self` is a safe reference.
402 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
403 unsafe { &*i.get_unchecked(self) }
406 /// Returns a mutable, unchecked subslice of `str`.
408 /// This is the unchecked alternative to indexing the `str`.
412 /// Callers of this function are responsible that these preconditions are
415 /// * The starting index must not exceed the ending index;
416 /// * Indexes must be within bounds of the original slice;
417 /// * Indexes must lie on UTF-8 sequence boundaries.
419 /// Failing that, the returned string slice may reference invalid memory or
420 /// violate the invariants communicated by the `str` type.
425 /// let mut v = String::from("🗻∈🌏");
427 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
428 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
429 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
432 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
434 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
435 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
436 // the slice is dereferencable because `self` is a safe reference.
437 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
438 unsafe { &mut *i.get_unchecked_mut(self) }
441 /// Creates a string slice from another string slice, bypassing safety
444 /// This is generally not recommended, use with caution! For a safe
445 /// alternative see [`str`] and [`Index`].
447 /// [`Index`]: crate::ops::Index
449 /// This new slice goes from `begin` to `end`, including `begin` but
452 /// To get a mutable string slice instead, see the
453 /// [`slice_mut_unchecked`] method.
455 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
459 /// Callers of this function are responsible that three preconditions are
462 /// * `begin` must not exceed `end`.
463 /// * `begin` and `end` must be byte positions within the string slice.
464 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
471 /// let s = "Löwe 老虎 Léopard";
474 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
477 /// let s = "Hello, world!";
480 /// assert_eq!("world", s.slice_unchecked(7, 12));
483 #[stable(feature = "rust1", since = "1.0.0")]
484 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
486 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
487 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
488 // the slice is dereferencable because `self` is a safe reference.
489 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
490 unsafe { &*(begin..end).get_unchecked(self) }
493 /// Creates a string slice from another string slice, bypassing safety
495 /// This is generally not recommended, use with caution! For a safe
496 /// alternative see [`str`] and [`IndexMut`].
498 /// [`IndexMut`]: crate::ops::IndexMut
500 /// This new slice goes from `begin` to `end`, including `begin` but
503 /// To get an immutable string slice instead, see the
504 /// [`slice_unchecked`] method.
506 /// [`slice_unchecked`]: str::slice_unchecked
510 /// Callers of this function are responsible that three preconditions are
513 /// * `begin` must not exceed `end`.
514 /// * `begin` and `end` must be byte positions within the string slice.
515 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
516 #[stable(feature = "str_slice_mut", since = "1.5.0")]
517 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
519 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
520 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
521 // the slice is dereferencable because `self` is a safe reference.
522 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
523 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
526 /// Divide one string slice into two at an index.
528 /// The argument, `mid`, should be a byte offset from the start of the
529 /// string. It must also be on the boundary of a UTF-8 code point.
531 /// The two slices returned go from the start of the string slice to `mid`,
532 /// and from `mid` to the end of the string slice.
534 /// To get mutable string slices instead, see the [`split_at_mut`]
537 /// [`split_at_mut`]: str::split_at_mut
541 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
542 /// past the end of the last code point of the string slice.
549 /// let s = "Per Martin-Löf";
551 /// let (first, last) = s.split_at(3);
553 /// assert_eq!("Per", first);
554 /// assert_eq!(" Martin-Löf", last);
557 #[stable(feature = "str_split_at", since = "1.4.0")]
558 pub fn split_at(&self, mid: usize) -> (&str, &str) {
559 // is_char_boundary checks that the index is in [0, .len()]
560 if self.is_char_boundary(mid) {
561 // SAFETY: just checked that `mid` is on a char boundary.
562 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
564 slice_error_fail(self, 0, mid)
568 /// Divide one mutable string slice into two at an index.
570 /// The argument, `mid`, should be a byte offset from the start of the
571 /// string. It must also be on the boundary of a UTF-8 code point.
573 /// The two slices returned go from the start of the string slice to `mid`,
574 /// and from `mid` to the end of the string slice.
576 /// To get immutable string slices instead, see the [`split_at`] method.
578 /// [`split_at`]: str::split_at
582 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
583 /// past the end of the last code point of the string slice.
590 /// let mut s = "Per Martin-Löf".to_string();
592 /// let (first, last) = s.split_at_mut(3);
593 /// first.make_ascii_uppercase();
594 /// assert_eq!("PER", first);
595 /// assert_eq!(" Martin-Löf", last);
597 /// assert_eq!("PER Martin-Löf", s);
600 #[stable(feature = "str_split_at", since = "1.4.0")]
601 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
602 // is_char_boundary checks that the index is in [0, .len()]
603 if self.is_char_boundary(mid) {
604 let len = self.len();
605 let ptr = self.as_mut_ptr();
606 // SAFETY: just checked that `mid` is on a char boundary.
609 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
610 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
614 slice_error_fail(self, 0, mid)
618 /// Returns an iterator over the [`char`]s of a string slice.
620 /// As a string slice consists of valid UTF-8, we can iterate through a
621 /// string slice by [`char`]. This method returns such an iterator.
623 /// It's important to remember that [`char`] represents a Unicode Scalar
624 /// Value, and may not match your idea of what a 'character' is. Iteration
625 /// over grapheme clusters may be what you actually want. This functionality
626 /// is not provided by Rust's standard library, check crates.io instead.
633 /// let word = "goodbye";
635 /// let count = word.chars().count();
636 /// assert_eq!(7, count);
638 /// let mut chars = word.chars();
640 /// assert_eq!(Some('g'), chars.next());
641 /// assert_eq!(Some('o'), chars.next());
642 /// assert_eq!(Some('o'), chars.next());
643 /// assert_eq!(Some('d'), chars.next());
644 /// assert_eq!(Some('b'), chars.next());
645 /// assert_eq!(Some('y'), chars.next());
646 /// assert_eq!(Some('e'), chars.next());
648 /// assert_eq!(None, chars.next());
651 /// Remember, [`char`]s may not match your intuition about characters:
653 /// [`char`]: prim@char
658 /// let mut chars = y.chars();
660 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
661 /// assert_eq!(Some('\u{0306}'), chars.next());
663 /// assert_eq!(None, chars.next());
665 #[stable(feature = "rust1", since = "1.0.0")]
667 pub fn chars(&self) -> Chars<'_> {
668 Chars { iter: self.as_bytes().iter() }
671 /// Returns an iterator over the [`char`]s of a string slice, and their
674 /// As a string slice consists of valid UTF-8, we can iterate through a
675 /// string slice by [`char`]. This method returns an iterator of both
676 /// these [`char`]s, as well as their byte positions.
678 /// The iterator yields tuples. The position is first, the [`char`] is
686 /// let word = "goodbye";
688 /// let count = word.char_indices().count();
689 /// assert_eq!(7, count);
691 /// let mut char_indices = word.char_indices();
693 /// assert_eq!(Some((0, 'g')), char_indices.next());
694 /// assert_eq!(Some((1, 'o')), char_indices.next());
695 /// assert_eq!(Some((2, 'o')), char_indices.next());
696 /// assert_eq!(Some((3, 'd')), char_indices.next());
697 /// assert_eq!(Some((4, 'b')), char_indices.next());
698 /// assert_eq!(Some((5, 'y')), char_indices.next());
699 /// assert_eq!(Some((6, 'e')), char_indices.next());
701 /// assert_eq!(None, char_indices.next());
704 /// Remember, [`char`]s may not match your intuition about characters:
706 /// [`char`]: prim@char
709 /// let yes = "y̆es";
711 /// let mut char_indices = yes.char_indices();
713 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
714 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
716 /// // note the 3 here - the last character took up two bytes
717 /// assert_eq!(Some((3, 'e')), char_indices.next());
718 /// assert_eq!(Some((4, 's')), char_indices.next());
720 /// assert_eq!(None, char_indices.next());
722 #[stable(feature = "rust1", since = "1.0.0")]
724 pub fn char_indices(&self) -> CharIndices<'_> {
725 CharIndices { front_offset: 0, iter: self.chars() }
728 /// An iterator over the bytes of a string slice.
730 /// As a string slice consists of a sequence of bytes, we can iterate
731 /// through a string slice by byte. This method returns such an iterator.
738 /// let mut bytes = "bors".bytes();
740 /// assert_eq!(Some(b'b'), bytes.next());
741 /// assert_eq!(Some(b'o'), bytes.next());
742 /// assert_eq!(Some(b'r'), bytes.next());
743 /// assert_eq!(Some(b's'), bytes.next());
745 /// assert_eq!(None, bytes.next());
747 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn bytes(&self) -> Bytes<'_> {
750 Bytes(self.as_bytes().iter().copied())
753 /// Splits a string slice by whitespace.
755 /// The iterator returned will return string slices that are sub-slices of
756 /// the original string slice, separated by any amount of whitespace.
758 /// 'Whitespace' is defined according to the terms of the Unicode Derived
759 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
760 /// instead, use [`split_ascii_whitespace`].
762 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
769 /// let mut iter = "A few words".split_whitespace();
771 /// assert_eq!(Some("A"), iter.next());
772 /// assert_eq!(Some("few"), iter.next());
773 /// assert_eq!(Some("words"), iter.next());
775 /// assert_eq!(None, iter.next());
778 /// All kinds of whitespace are considered:
781 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
782 /// assert_eq!(Some("Mary"), iter.next());
783 /// assert_eq!(Some("had"), iter.next());
784 /// assert_eq!(Some("a"), iter.next());
785 /// assert_eq!(Some("little"), iter.next());
786 /// assert_eq!(Some("lamb"), iter.next());
788 /// assert_eq!(None, iter.next());
790 #[stable(feature = "split_whitespace", since = "1.1.0")]
792 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
793 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
796 /// Splits a string slice by ASCII whitespace.
798 /// The iterator returned will return string slices that are sub-slices of
799 /// the original string slice, separated by any amount of ASCII whitespace.
801 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
803 /// [`split_whitespace`]: str::split_whitespace
810 /// let mut iter = "A few words".split_ascii_whitespace();
812 /// assert_eq!(Some("A"), iter.next());
813 /// assert_eq!(Some("few"), iter.next());
814 /// assert_eq!(Some("words"), iter.next());
816 /// assert_eq!(None, iter.next());
819 /// All kinds of ASCII whitespace are considered:
822 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
823 /// assert_eq!(Some("Mary"), iter.next());
824 /// assert_eq!(Some("had"), iter.next());
825 /// assert_eq!(Some("a"), iter.next());
826 /// assert_eq!(Some("little"), iter.next());
827 /// assert_eq!(Some("lamb"), iter.next());
829 /// assert_eq!(None, iter.next());
831 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
833 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
835 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
836 SplitAsciiWhitespace { inner }
839 /// An iterator over the lines of a string, as string slices.
841 /// Lines are ended with either a newline (`\n`) or a carriage return with
842 /// a line feed (`\r\n`).
844 /// The final line ending is optional. A string that ends with a final line
845 /// ending will return the same lines as an otherwise identical string
846 /// without a final line ending.
853 /// let text = "foo\r\nbar\n\nbaz\n";
854 /// let mut lines = text.lines();
856 /// assert_eq!(Some("foo"), lines.next());
857 /// assert_eq!(Some("bar"), lines.next());
858 /// assert_eq!(Some(""), lines.next());
859 /// assert_eq!(Some("baz"), lines.next());
861 /// assert_eq!(None, lines.next());
864 /// The final line ending isn't required:
867 /// let text = "foo\nbar\n\r\nbaz";
868 /// let mut lines = text.lines();
870 /// assert_eq!(Some("foo"), lines.next());
871 /// assert_eq!(Some("bar"), lines.next());
872 /// assert_eq!(Some(""), lines.next());
873 /// assert_eq!(Some("baz"), lines.next());
875 /// assert_eq!(None, lines.next());
877 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn lines(&self) -> Lines<'_> {
880 Lines(self.split_terminator('\n').map(LinesAnyMap))
883 /// An iterator over the lines of a string.
884 #[stable(feature = "rust1", since = "1.0.0")]
885 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
888 pub fn lines_any(&self) -> LinesAny<'_> {
889 LinesAny(self.lines())
892 /// Returns an iterator of `u16` over the string encoded as UTF-16.
899 /// let text = "Zażółć gęślą jaźń";
901 /// let utf8_len = text.len();
902 /// let utf16_len = text.encode_utf16().count();
904 /// assert!(utf16_len <= utf8_len);
906 #[stable(feature = "encode_utf16", since = "1.8.0")]
907 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
908 EncodeUtf16 { chars: self.chars(), extra: 0 }
911 /// Returns `true` if the given pattern matches a sub-slice of
912 /// this string slice.
914 /// Returns `false` if it does not.
916 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
917 /// function or closure that determines if a character matches.
919 /// [`char`]: prim@char
920 /// [pattern]: self::pattern
927 /// let bananas = "bananas";
929 /// assert!(bananas.contains("nana"));
930 /// assert!(!bananas.contains("apples"));
932 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
935 pat.is_contained_in(self)
938 /// Returns `true` if the given pattern matches a prefix of this
941 /// Returns `false` if it does not.
943 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
944 /// function or closure that determines if a character matches.
946 /// [`char`]: prim@char
947 /// [pattern]: self::pattern
954 /// let bananas = "bananas";
956 /// assert!(bananas.starts_with("bana"));
957 /// assert!(!bananas.starts_with("nana"));
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
961 pat.is_prefix_of(self)
964 /// Returns `true` if the given pattern matches a suffix of this
967 /// Returns `false` if it does not.
969 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
970 /// function or closure that determines if a character matches.
972 /// [`char`]: prim@char
973 /// [pattern]: self::pattern
980 /// let bananas = "bananas";
982 /// assert!(bananas.ends_with("anas"));
983 /// assert!(!bananas.ends_with("nana"));
985 #[stable(feature = "rust1", since = "1.0.0")]
986 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
988 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
990 pat.is_suffix_of(self)
993 /// Returns the byte index of the first character of this string slice that
994 /// matches the pattern.
996 /// Returns [`None`] if the pattern doesn't match.
998 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
999 /// function or closure that determines if a character matches.
1001 /// [`char`]: prim@char
1002 /// [pattern]: self::pattern
1006 /// Simple patterns:
1009 /// let s = "Löwe 老虎 Léopard Gepardi";
1011 /// assert_eq!(s.find('L'), Some(0));
1012 /// assert_eq!(s.find('é'), Some(14));
1013 /// assert_eq!(s.find("pard"), Some(17));
1016 /// More complex patterns using point-free style and closures:
1019 /// let s = "Löwe 老虎 Léopard";
1021 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1022 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1023 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1024 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1027 /// Not finding the pattern:
1030 /// let s = "Löwe 老虎 Léopard";
1031 /// let x: &[_] = &['1', '2'];
1033 /// assert_eq!(s.find(x), None);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1038 pat.into_searcher(self).next_match().map(|(i, _)| i)
1041 /// Returns the byte index for the first character of the rightmost match of the pattern in
1042 /// this string slice.
1044 /// Returns [`None`] if the pattern doesn't match.
1046 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1047 /// function or closure that determines if a character matches.
1049 /// [`char`]: prim@char
1050 /// [pattern]: self::pattern
1054 /// Simple patterns:
1057 /// let s = "Löwe 老虎 Léopard Gepardi";
1059 /// assert_eq!(s.rfind('L'), Some(13));
1060 /// assert_eq!(s.rfind('é'), Some(14));
1061 /// assert_eq!(s.rfind("pard"), Some(24));
1064 /// More complex patterns with closures:
1067 /// let s = "Löwe 老虎 Léopard";
1069 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1070 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1073 /// Not finding the pattern:
1076 /// let s = "Löwe 老虎 Léopard";
1077 /// let x: &[_] = &['1', '2'];
1079 /// assert_eq!(s.rfind(x), None);
1081 #[stable(feature = "rust1", since = "1.0.0")]
1083 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1085 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1087 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1090 /// An iterator over substrings of this string slice, separated by
1091 /// characters matched by a pattern.
1093 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1094 /// function or closure that determines if a character matches.
1096 /// [`char`]: prim@char
1097 /// [pattern]: self::pattern
1099 /// # Iterator behavior
1101 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1102 /// allows a reverse search and forward/reverse search yields the same
1103 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1105 /// If the pattern allows a reverse search but its results might differ
1106 /// from a forward search, the [`rsplit`] method can be used.
1108 /// [`rsplit`]: str::rsplit
1112 /// Simple patterns:
1115 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1116 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1118 /// let v: Vec<&str> = "".split('X').collect();
1119 /// assert_eq!(v, [""]);
1121 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1122 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1124 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1125 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1127 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1128 /// assert_eq!(v, ["abc", "def", "ghi"]);
1130 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1131 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1134 /// A more complex pattern, using a closure:
1137 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1138 /// assert_eq!(v, ["abc", "def", "ghi"]);
1141 /// If a string contains multiple contiguous separators, you will end up
1142 /// with empty strings in the output:
1145 /// let x = "||||a||b|c".to_string();
1146 /// let d: Vec<_> = x.split('|').collect();
1148 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1151 /// Contiguous separators are separated by the empty string.
1154 /// let x = "(///)".to_string();
1155 /// let d: Vec<_> = x.split('/').collect();
1157 /// assert_eq!(d, &["(", "", "", ")"]);
1160 /// Separators at the start or end of a string are neighbored
1161 /// by empty strings.
1164 /// let d: Vec<_> = "010".split("0").collect();
1165 /// assert_eq!(d, &["", "1", ""]);
1168 /// When the empty string is used as a separator, it separates
1169 /// every character in the string, along with the beginning
1170 /// and end of the string.
1173 /// let f: Vec<_> = "rust".split("").collect();
1174 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1177 /// Contiguous separators can lead to possibly surprising behavior
1178 /// when whitespace is used as the separator. This code is correct:
1181 /// let x = " a b c".to_string();
1182 /// let d: Vec<_> = x.split(' ').collect();
1184 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1187 /// It does _not_ give you:
1190 /// assert_eq!(d, &["a", "b", "c"]);
1193 /// Use [`split_whitespace`] for this behavior.
1195 /// [`split_whitespace`]: str::split_whitespace
1196 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1199 Split(SplitInternal {
1202 matcher: pat.into_searcher(self),
1203 allow_trailing_empty: true,
1208 /// An iterator over substrings of this string slice, separated by
1209 /// characters matched by a pattern. Differs from the iterator produced by
1210 /// `split` in that `split_inclusive` leaves the matched part as the
1211 /// terminator of the substring.
1213 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1214 /// function or closure that determines if a character matches.
1216 /// [`char`]: prim@char
1217 /// [pattern]: self::pattern
1222 /// #![feature(split_inclusive)]
1223 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1224 /// .split_inclusive('\n').collect();
1225 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1228 /// If the last element of the string is matched,
1229 /// that element will be considered the terminator of the preceding substring.
1230 /// That substring will be the last item returned by the iterator.
1233 /// #![feature(split_inclusive)]
1234 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1235 /// .split_inclusive('\n').collect();
1236 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1238 #[unstable(feature = "split_inclusive", issue = "72360")]
1240 pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1241 SplitInclusive(SplitInternal {
1244 matcher: pat.into_searcher(self),
1245 allow_trailing_empty: false,
1250 /// An iterator over substrings of the given string slice, separated by
1251 /// characters matched by a pattern and yielded in reverse order.
1253 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1254 /// function or closure that determines if a character matches.
1256 /// [`char`]: prim@char
1257 /// [pattern]: self::pattern
1259 /// # Iterator behavior
1261 /// The returned iterator requires that the pattern supports a reverse
1262 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1263 /// search yields the same elements.
1265 /// For iterating from the front, the [`split`] method can be used.
1267 /// [`split`]: str::split
1271 /// Simple patterns:
1274 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1275 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1277 /// let v: Vec<&str> = "".rsplit('X').collect();
1278 /// assert_eq!(v, [""]);
1280 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1281 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1283 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1284 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1287 /// A more complex pattern, using a closure:
1290 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1291 /// assert_eq!(v, ["ghi", "def", "abc"]);
1293 #[stable(feature = "rust1", since = "1.0.0")]
1295 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1297 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1299 RSplit(self.split(pat).0)
1302 /// An iterator over substrings of the given string slice, separated by
1303 /// characters matched by a pattern.
1305 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1306 /// function or closure that determines if a character matches.
1308 /// [`char`]: prim@char
1309 /// [pattern]: self::pattern
1311 /// Equivalent to [`split`], except that the trailing substring
1312 /// is skipped if empty.
1314 /// [`split`]: str::split
1316 /// This method can be used for string data that is _terminated_,
1317 /// rather than _separated_ by a pattern.
1319 /// # Iterator behavior
1321 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1322 /// allows a reverse search and forward/reverse search yields the same
1323 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1325 /// If the pattern allows a reverse search but its results might differ
1326 /// from a forward search, the [`rsplit_terminator`] method can be used.
1328 /// [`rsplit_terminator`]: str::rsplit_terminator
1335 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1336 /// assert_eq!(v, ["A", "B"]);
1338 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1339 /// assert_eq!(v, ["A", "", "B", ""]);
1341 #[stable(feature = "rust1", since = "1.0.0")]
1343 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1344 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1347 /// An iterator over substrings of `self`, separated by characters
1348 /// matched by a pattern and yielded in reverse order.
1350 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1351 /// function or closure that determines if a character matches.
1353 /// [`char`]: prim@char
1354 /// [pattern]: self::pattern
1356 /// Equivalent to [`split`], except that the trailing substring is
1357 /// skipped if empty.
1359 /// [`split`]: str::split
1361 /// This method can be used for string data that is _terminated_,
1362 /// rather than _separated_ by a pattern.
1364 /// # Iterator behavior
1366 /// The returned iterator requires that the pattern supports a
1367 /// reverse search, and it will be double ended if a forward/reverse
1368 /// search yields the same elements.
1370 /// For iterating from the front, the [`split_terminator`] method can be
1373 /// [`split_terminator`]: str::split_terminator
1378 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1379 /// assert_eq!(v, ["B", "A"]);
1381 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1382 /// assert_eq!(v, ["", "B", "", "A"]);
1384 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1388 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1390 RSplitTerminator(self.split_terminator(pat).0)
1393 /// An iterator over substrings of the given string slice, separated by a
1394 /// pattern, restricted to returning at most `n` items.
1396 /// If `n` substrings are returned, the last substring (the `n`th substring)
1397 /// will contain the remainder of the string.
1399 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1400 /// function or closure that determines if a character matches.
1402 /// [`char`]: prim@char
1403 /// [pattern]: self::pattern
1405 /// # Iterator behavior
1407 /// The returned iterator will not be double ended, because it is
1408 /// not efficient to support.
1410 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1413 /// [`rsplitn`]: str::rsplitn
1417 /// Simple patterns:
1420 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1421 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1423 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1424 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1426 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1427 /// assert_eq!(v, ["abcXdef"]);
1429 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1430 /// assert_eq!(v, [""]);
1433 /// A more complex pattern, using a closure:
1436 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1437 /// assert_eq!(v, ["abc", "defXghi"]);
1439 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1442 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1445 /// An iterator over substrings of this string slice, separated by a
1446 /// pattern, starting from the end of the string, restricted to returning
1447 /// at most `n` items.
1449 /// If `n` substrings are returned, the last substring (the `n`th substring)
1450 /// will contain the remainder of the string.
1452 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1453 /// function or closure that determines if a character matches.
1455 /// [`char`]: prim@char
1456 /// [pattern]: self::pattern
1458 /// # Iterator behavior
1460 /// The returned iterator will not be double ended, because it is not
1461 /// efficient to support.
1463 /// For splitting from the front, the [`splitn`] method can be used.
1465 /// [`splitn`]: str::splitn
1469 /// Simple patterns:
1472 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1473 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1475 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1476 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1478 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1479 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1482 /// A more complex pattern, using a closure:
1485 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1486 /// assert_eq!(v, ["ghi", "abc1def"]);
1488 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1492 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1494 RSplitN(self.splitn(n, pat).0)
1497 /// Splits the string on the first occurrence of the specified delimiter and
1498 /// returns prefix before delimiter and suffix after delimiter.
1503 /// #![feature(str_split_once)]
1505 /// assert_eq!("cfg".split_once('='), None);
1506 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1507 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1509 #[unstable(feature = "str_split_once", reason = "newly added", issue = "74773")]
1511 pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1512 let (start, end) = delimiter.into_searcher(self).next_match()?;
1513 Some((&self[..start], &self[end..]))
1516 /// Splits the string on the last occurrence of the specified delimiter and
1517 /// returns prefix before delimiter and suffix after delimiter.
1522 /// #![feature(str_split_once)]
1524 /// assert_eq!("cfg".rsplit_once('='), None);
1525 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1526 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1528 #[unstable(feature = "str_split_once", reason = "newly added", issue = "74773")]
1530 pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1532 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1534 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1535 Some((&self[..start], &self[end..]))
1538 /// An iterator over the disjoint matches of a pattern within the given string
1541 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1542 /// function or closure that determines if a character matches.
1544 /// [`char`]: prim@char
1545 /// [pattern]: self::pattern
1547 /// # Iterator behavior
1549 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1550 /// allows a reverse search and forward/reverse search yields the same
1551 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1553 /// If the pattern allows a reverse search but its results might differ
1554 /// from a forward search, the [`rmatches`] method can be used.
1556 /// [`rmatches`]: str::matches
1563 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1564 /// assert_eq!(v, ["abc", "abc", "abc"]);
1566 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1567 /// assert_eq!(v, ["1", "2", "3"]);
1569 #[stable(feature = "str_matches", since = "1.2.0")]
1571 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1572 Matches(MatchesInternal(pat.into_searcher(self)))
1575 /// An iterator over the disjoint matches of a pattern within this string slice,
1576 /// yielded in reverse order.
1578 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1579 /// function or closure that determines if a character matches.
1581 /// [`char`]: prim@char
1582 /// [pattern]: self::pattern
1584 /// # Iterator behavior
1586 /// The returned iterator requires that the pattern supports a reverse
1587 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1588 /// search yields the same elements.
1590 /// For iterating from the front, the [`matches`] method can be used.
1592 /// [`matches`]: str::matches
1599 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1600 /// assert_eq!(v, ["abc", "abc", "abc"]);
1602 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1603 /// assert_eq!(v, ["3", "2", "1"]);
1605 #[stable(feature = "str_matches", since = "1.2.0")]
1607 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1609 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1611 RMatches(self.matches(pat).0)
1614 /// An iterator over the disjoint matches of a pattern within this string
1615 /// slice as well as the index that the match starts at.
1617 /// For matches of `pat` within `self` that overlap, only the indices
1618 /// corresponding to the first match are returned.
1620 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1621 /// function or closure that determines if a character matches.
1623 /// [`char`]: prim@char
1624 /// [pattern]: self::pattern
1626 /// # Iterator behavior
1628 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1629 /// allows a reverse search and forward/reverse search yields the same
1630 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1632 /// If the pattern allows a reverse search but its results might differ
1633 /// from a forward search, the [`rmatch_indices`] method can be used.
1635 /// [`rmatch_indices`]: str::match_indices
1642 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1643 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1645 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1646 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1648 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1649 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1651 #[stable(feature = "str_match_indices", since = "1.5.0")]
1653 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1654 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1657 /// An iterator over the disjoint matches of a pattern within `self`,
1658 /// yielded in reverse order along with the index of the match.
1660 /// For matches of `pat` within `self` that overlap, only the indices
1661 /// corresponding to the last match are returned.
1663 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1664 /// function or closure that determines if a character matches.
1666 /// [`char`]: prim@char
1667 /// [pattern]: self::pattern
1669 /// # Iterator behavior
1671 /// The returned iterator requires that the pattern supports a reverse
1672 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1673 /// search yields the same elements.
1675 /// For iterating from the front, the [`match_indices`] method can be used.
1677 /// [`match_indices`]: str::match_indices
1684 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1685 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1687 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1688 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1690 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1691 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1693 #[stable(feature = "str_match_indices", since = "1.5.0")]
1695 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1697 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1699 RMatchIndices(self.match_indices(pat).0)
1702 /// Returns a string slice with leading and trailing whitespace removed.
1704 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1705 /// Core Property `White_Space`.
1712 /// let s = " Hello\tworld\t";
1714 /// assert_eq!("Hello\tworld", s.trim());
1717 #[must_use = "this returns the trimmed string as a slice, \
1718 without modifying the original"]
1719 #[stable(feature = "rust1", since = "1.0.0")]
1720 pub fn trim(&self) -> &str {
1721 self.trim_matches(|c: char| c.is_whitespace())
1724 /// Returns a string slice with leading whitespace removed.
1726 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1727 /// Core Property `White_Space`.
1729 /// # Text directionality
1731 /// A string is a sequence of bytes. `start` in this context means the first
1732 /// position of that byte string; for a left-to-right language like English or
1733 /// Russian, this will be left side, and for right-to-left languages like
1734 /// Arabic or Hebrew, this will be the right side.
1741 /// let s = " Hello\tworld\t";
1742 /// assert_eq!("Hello\tworld\t", s.trim_start());
1748 /// let s = " English ";
1749 /// assert!(Some('E') == s.trim_start().chars().next());
1751 /// let s = " עברית ";
1752 /// assert!(Some('ע') == s.trim_start().chars().next());
1755 #[must_use = "this returns the trimmed string as a new slice, \
1756 without modifying the original"]
1757 #[stable(feature = "trim_direction", since = "1.30.0")]
1758 pub fn trim_start(&self) -> &str {
1759 self.trim_start_matches(|c: char| c.is_whitespace())
1762 /// Returns a string slice with trailing whitespace removed.
1764 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1765 /// Core Property `White_Space`.
1767 /// # Text directionality
1769 /// A string is a sequence of bytes. `end` in this context means the last
1770 /// position of that byte string; for a left-to-right language like English or
1771 /// Russian, this will be right side, and for right-to-left languages like
1772 /// Arabic or Hebrew, this will be the left side.
1779 /// let s = " Hello\tworld\t";
1780 /// assert_eq!(" Hello\tworld", s.trim_end());
1786 /// let s = " English ";
1787 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1789 /// let s = " עברית ";
1790 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1793 #[must_use = "this returns the trimmed string as a new slice, \
1794 without modifying the original"]
1795 #[stable(feature = "trim_direction", since = "1.30.0")]
1796 pub fn trim_end(&self) -> &str {
1797 self.trim_end_matches(|c: char| c.is_whitespace())
1800 /// Returns a string slice with leading whitespace removed.
1802 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1803 /// Core Property `White_Space`.
1805 /// # Text directionality
1807 /// A string is a sequence of bytes. 'Left' in this context means the first
1808 /// position of that byte string; for a language like Arabic or Hebrew
1809 /// which are 'right to left' rather than 'left to right', this will be
1810 /// the _right_ side, not the left.
1817 /// let s = " Hello\tworld\t";
1819 /// assert_eq!("Hello\tworld\t", s.trim_left());
1825 /// let s = " English";
1826 /// assert!(Some('E') == s.trim_left().chars().next());
1828 /// let s = " עברית";
1829 /// assert!(Some('ע') == s.trim_left().chars().next());
1832 #[stable(feature = "rust1", since = "1.0.0")]
1835 reason = "superseded by `trim_start`",
1836 suggestion = "trim_start"
1838 pub fn trim_left(&self) -> &str {
1842 /// Returns a string slice with trailing whitespace removed.
1844 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1845 /// Core Property `White_Space`.
1847 /// # Text directionality
1849 /// A string is a sequence of bytes. 'Right' in this context means the last
1850 /// position of that byte string; for a language like Arabic or Hebrew
1851 /// which are 'right to left' rather than 'left to right', this will be
1852 /// the _left_ side, not the right.
1859 /// let s = " Hello\tworld\t";
1861 /// assert_eq!(" Hello\tworld", s.trim_right());
1867 /// let s = "English ";
1868 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1870 /// let s = "עברית ";
1871 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1874 #[stable(feature = "rust1", since = "1.0.0")]
1877 reason = "superseded by `trim_end`",
1878 suggestion = "trim_end"
1880 pub fn trim_right(&self) -> &str {
1884 /// Returns a string slice with all prefixes and suffixes that match a
1885 /// pattern repeatedly removed.
1887 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
1888 /// or closure that determines if a character matches.
1890 /// [`char`]: prim@char
1891 /// [pattern]: self::pattern
1895 /// Simple patterns:
1898 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1899 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1901 /// let x: &[_] = &['1', '2'];
1902 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1905 /// A more complex pattern, using a closure:
1908 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1910 #[must_use = "this returns the trimmed string as a new slice, \
1911 without modifying the original"]
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
1915 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
1919 let mut matcher = pat.into_searcher(self);
1920 if let Some((a, b)) = matcher.next_reject() {
1922 j = b; // Remember earliest known match, correct it below if
1923 // last match is different
1925 if let Some((_, b)) = matcher.next_reject_back() {
1928 // SAFETY: `Searcher` is known to return valid indices.
1929 unsafe { self.get_unchecked(i..j) }
1932 /// Returns a string slice with all prefixes that match a pattern
1933 /// repeatedly removed.
1935 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1936 /// function or closure that determines if a character matches.
1938 /// [`char`]: prim@char
1939 /// [pattern]: self::pattern
1941 /// # Text directionality
1943 /// A string is a sequence of bytes. `start` in this context means the first
1944 /// position of that byte string; for a left-to-right language like English or
1945 /// Russian, this will be left side, and for right-to-left languages like
1946 /// Arabic or Hebrew, this will be the right side.
1953 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
1954 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
1956 /// let x: &[_] = &['1', '2'];
1957 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1959 #[must_use = "this returns the trimmed string as a new slice, \
1960 without modifying the original"]
1961 #[stable(feature = "trim_direction", since = "1.30.0")]
1962 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1963 let mut i = self.len();
1964 let mut matcher = pat.into_searcher(self);
1965 if let Some((a, _)) = matcher.next_reject() {
1968 // SAFETY: `Searcher` is known to return valid indices.
1969 unsafe { self.get_unchecked(i..self.len()) }
1972 /// Returns a string slice with the prefix removed.
1974 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
1975 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
1977 /// If the string does not start with `prefix`, returns `None`.
1979 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1980 /// function or closure that determines if a character matches.
1982 /// [`char`]: prim@char
1983 /// [pattern]: self::pattern
1988 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
1989 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
1990 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
1992 #[must_use = "this returns the remaining substring as a new slice, \
1993 without modifying the original"]
1994 #[stable(feature = "str_strip", since = "1.45.0")]
1995 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
1996 prefix.strip_prefix_of(self)
1999 /// Returns a string slice with the suffix removed.
2001 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2002 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2004 /// If the string does not end with `suffix`, returns `None`.
2006 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2007 /// function or closure that determines if a character matches.
2009 /// [`char`]: prim@char
2010 /// [pattern]: self::pattern
2015 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2016 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2017 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2019 #[must_use = "this returns the remaining substring as a new slice, \
2020 without modifying the original"]
2021 #[stable(feature = "str_strip", since = "1.45.0")]
2022 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2025 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2027 suffix.strip_suffix_of(self)
2030 /// Returns a string slice with all suffixes that match a pattern
2031 /// repeatedly removed.
2033 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2034 /// function or closure that determines if a character matches.
2036 /// [`char`]: prim@char
2037 /// [pattern]: self::pattern
2039 /// # Text directionality
2041 /// A string is a sequence of bytes. `end` in this context means the last
2042 /// position of that byte string; for a left-to-right language like English or
2043 /// Russian, this will be right side, and for right-to-left languages like
2044 /// Arabic or Hebrew, this will be the left side.
2048 /// Simple patterns:
2051 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2052 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2054 /// let x: &[_] = &['1', '2'];
2055 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2058 /// A more complex pattern, using a closure:
2061 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2063 #[must_use = "this returns the trimmed string as a new slice, \
2064 without modifying the original"]
2065 #[stable(feature = "trim_direction", since = "1.30.0")]
2066 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2068 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2071 let mut matcher = pat.into_searcher(self);
2072 if let Some((_, b)) = matcher.next_reject_back() {
2075 // SAFETY: `Searcher` is known to return valid indices.
2076 unsafe { self.get_unchecked(0..j) }
2079 /// Returns a string slice with all prefixes that match a pattern
2080 /// repeatedly removed.
2082 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2083 /// function or closure that determines if a character matches.
2085 /// [`char`]: prim@char
2086 /// [pattern]: self::pattern
2088 /// # Text directionality
2090 /// A string is a sequence of bytes. 'Left' in this context means the first
2091 /// position of that byte string; for a language like Arabic or Hebrew
2092 /// which are 'right to left' rather than 'left to right', this will be
2093 /// the _right_ side, not the left.
2100 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2101 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2103 /// let x: &[_] = &['1', '2'];
2104 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2106 #[stable(feature = "rust1", since = "1.0.0")]
2109 reason = "superseded by `trim_start_matches`",
2110 suggestion = "trim_start_matches"
2112 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2113 self.trim_start_matches(pat)
2116 /// Returns a string slice with all suffixes that match a pattern
2117 /// repeatedly removed.
2119 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2120 /// function or closure that determines if a character matches.
2122 /// [`char`]: prim@char
2123 /// [pattern]: self::pattern
2125 /// # Text directionality
2127 /// A string is a sequence of bytes. 'Right' in this context means the last
2128 /// position of that byte string; for a language like Arabic or Hebrew
2129 /// which are 'right to left' rather than 'left to right', this will be
2130 /// the _left_ side, not the right.
2134 /// Simple patterns:
2137 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2138 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2140 /// let x: &[_] = &['1', '2'];
2141 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2144 /// A more complex pattern, using a closure:
2147 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2149 #[stable(feature = "rust1", since = "1.0.0")]
2152 reason = "superseded by `trim_end_matches`",
2153 suggestion = "trim_end_matches"
2155 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2157 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2159 self.trim_end_matches(pat)
2162 /// Parses this string slice into another type.
2164 /// Because `parse` is so general, it can cause problems with type
2165 /// inference. As such, `parse` is one of the few times you'll see
2166 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2167 /// helps the inference algorithm understand specifically which type
2168 /// you're trying to parse into.
2170 /// `parse` can parse any type that implements the [`FromStr`] trait.
2175 /// Will return [`Err`] if it's not possible to parse this string slice into
2176 /// the desired type.
2178 /// [`Err`]: FromStr::Err
2185 /// let four: u32 = "4".parse().unwrap();
2187 /// assert_eq!(4, four);
2190 /// Using the 'turbofish' instead of annotating `four`:
2193 /// let four = "4".parse::<u32>();
2195 /// assert_eq!(Ok(4), four);
2198 /// Failing to parse:
2201 /// let nope = "j".parse::<u32>();
2203 /// assert!(nope.is_err());
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2208 FromStr::from_str(self)
2211 /// Checks if all characters in this string are within the ASCII range.
2216 /// let ascii = "hello!\n";
2217 /// let non_ascii = "Grüße, Jürgen ❤";
2219 /// assert!(ascii.is_ascii());
2220 /// assert!(!non_ascii.is_ascii());
2222 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2224 pub fn is_ascii(&self) -> bool {
2225 // We can treat each byte as character here: all multibyte characters
2226 // start with a byte that is not in the ascii range, so we will stop
2228 self.as_bytes().is_ascii()
2231 /// Checks that two strings are an ASCII case-insensitive match.
2233 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2234 /// but without allocating and copying temporaries.
2239 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2240 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2241 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2243 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2245 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2246 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2249 /// Converts this string to its ASCII upper case equivalent in-place.
2251 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2252 /// but non-ASCII letters are unchanged.
2254 /// To return a new uppercased value without modifying the existing one, use
2255 /// [`to_ascii_uppercase`].
2257 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2262 /// let mut s = String::from("Grüße, Jürgen ❤");
2264 /// s.make_ascii_uppercase();
2266 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2268 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2270 pub fn make_ascii_uppercase(&mut self) {
2271 // SAFETY: safe because we transmute two types with the same layout.
2272 let me = unsafe { self.as_bytes_mut() };
2273 me.make_ascii_uppercase()
2276 /// Converts this string to its ASCII lower case equivalent in-place.
2278 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2279 /// but non-ASCII letters are unchanged.
2281 /// To return a new lowercased value without modifying the existing one, use
2282 /// [`to_ascii_lowercase`].
2284 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2289 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2291 /// s.make_ascii_lowercase();
2293 /// assert_eq!("grÜße, jÜrgen ❤", s);
2295 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2297 pub fn make_ascii_lowercase(&mut self) {
2298 // SAFETY: safe because we transmute two types with the same layout.
2299 let me = unsafe { self.as_bytes_mut() };
2300 me.make_ascii_lowercase()
2303 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2305 /// Note: only extended grapheme codepoints that begin the string will be
2313 /// for c in "❤\n!".escape_debug() {
2314 /// print!("{}", c);
2319 /// Using `println!` directly:
2322 /// println!("{}", "❤\n!".escape_debug());
2326 /// Both are equivalent to:
2329 /// println!("❤\\n!");
2332 /// Using `to_string`:
2335 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2337 #[stable(feature = "str_escape", since = "1.34.0")]
2338 pub fn escape_debug(&self) -> EscapeDebug<'_> {
2339 let mut chars = self.chars();
2343 .map(|first| first.escape_debug_ext(true))
2346 .chain(chars.flat_map(CharEscapeDebugContinue)),
2350 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2357 /// for c in "❤\n!".escape_default() {
2358 /// print!("{}", c);
2363 /// Using `println!` directly:
2366 /// println!("{}", "❤\n!".escape_default());
2370 /// Both are equivalent to:
2373 /// println!("\\u{{2764}}\\n!");
2376 /// Using `to_string`:
2379 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2381 #[stable(feature = "str_escape", since = "1.34.0")]
2382 pub fn escape_default(&self) -> EscapeDefault<'_> {
2383 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2386 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2393 /// for c in "❤\n!".escape_unicode() {
2394 /// print!("{}", c);
2399 /// Using `println!` directly:
2402 /// println!("{}", "❤\n!".escape_unicode());
2406 /// Both are equivalent to:
2409 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2412 /// Using `to_string`:
2415 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2417 #[stable(feature = "str_escape", since = "1.34.0")]
2418 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2419 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2423 #[stable(feature = "rust1", since = "1.0.0")]
2424 impl AsRef<[u8]> for str {
2426 fn as_ref(&self) -> &[u8] {
2431 #[stable(feature = "rust1", since = "1.0.0")]
2432 impl Default for &str {
2433 /// Creates an empty str
2435 fn default() -> Self {
2440 #[stable(feature = "default_mut_str", since = "1.28.0")]
2441 impl Default for &mut str {
2442 /// Creates an empty mutable str
2444 fn default() -> Self {
2445 // SAFETY: The empty string is valid UTF-8.
2446 unsafe { from_utf8_unchecked_mut(&mut []) }
2451 /// A nameable, cloneable fn type
2453 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2455 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2460 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2461 c.escape_debug_ext(false)
2465 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2469 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2474 struct IsWhitespace impl Fn = |c: char| -> bool {
2479 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2480 byte.is_ascii_whitespace()
2484 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2489 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2494 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2496 unsafe { from_utf8_unchecked(bytes) }