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};
18 use crate::char::{self, EscapeDebugExtArgs};
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 #[stable(feature = "split_inclusive", since = "1.51.0")]
69 pub use iter::SplitInclusive;
71 #[unstable(feature = "str_internals", issue = "none")]
72 pub use validations::{next_code_point, utf8_char_width};
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 might 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.39.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.39.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 {
195 // Test for 0 explicitly so that it can optimize out the check
196 // easily and skip reading string data for that case.
197 // Note that optimizing `self.get(..index)` relies on this.
202 match self.as_bytes().get(index) {
203 // For `None` we have two options:
205 // - index == self.len()
206 // Empty strings are valid, so return true
207 // - index > self.len()
208 // In this case return false
210 // The check is placed exactly here, because it improves generated
211 // code on higher opt-levels. See PR #84751 for more details.
212 None => index == self.len(),
214 // This is bit magic equivalent to: b < 128 || b >= 192
215 Some(&b) => (b as i8) >= -0x40,
219 /// Converts a string slice to a byte slice. To convert the byte slice back
220 /// into a string slice, use the [`from_utf8`] function.
227 /// let bytes = "bors".as_bytes();
228 /// assert_eq!(b"bors", bytes);
230 #[stable(feature = "rust1", since = "1.0.0")]
231 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
233 #[allow(unused_attributes)]
234 pub const fn as_bytes(&self) -> &[u8] {
235 // SAFETY: const sound because we transmute two types with the same layout
236 unsafe { mem::transmute(self) }
239 /// Converts a mutable string slice to a mutable byte slice.
243 /// The caller must ensure that the content of the slice is valid UTF-8
244 /// before the borrow ends and the underlying `str` is used.
246 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
253 /// let mut s = String::from("Hello");
254 /// let bytes = unsafe { s.as_bytes_mut() };
256 /// assert_eq!(b"Hello", bytes);
262 /// let mut s = String::from("🗻∈🌏");
265 /// let bytes = s.as_bytes_mut();
273 /// assert_eq!("🍔∈🌏", s);
275 #[stable(feature = "str_mut_extras", since = "1.20.0")]
277 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
278 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
279 // has the same layout as `&[u8]` (only libstd can make this guarantee).
280 // The pointer dereference is safe since it comes from a mutable reference which
281 // is guaranteed to be valid for writes.
282 unsafe { &mut *(self as *mut str as *mut [u8]) }
285 /// Converts a string slice to a raw pointer.
287 /// As string slices are a slice of bytes, the raw pointer points to a
288 /// [`u8`]. This pointer will be pointing to the first byte of the string
291 /// The caller must ensure that the returned pointer is never written to.
292 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
294 /// [`as_mut_ptr`]: str::as_mut_ptr
302 /// let ptr = s.as_ptr();
304 #[stable(feature = "rust1", since = "1.0.0")]
305 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
307 pub const fn as_ptr(&self) -> *const u8 {
308 self as *const str as *const u8
311 /// Converts a mutable string slice to a raw pointer.
313 /// As string slices are a slice of bytes, the raw pointer points to a
314 /// [`u8`]. This pointer will be pointing to the first byte of the string
317 /// It is your responsibility to make sure that the string slice only gets
318 /// modified in a way that it remains valid UTF-8.
319 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
321 pub fn as_mut_ptr(&mut self) -> *mut u8 {
322 self as *mut str as *mut u8
325 /// Returns a subslice of `str`.
327 /// This is the non-panicking alternative to indexing the `str`. Returns
328 /// [`None`] whenever equivalent indexing operation would panic.
333 /// let v = String::from("🗻∈🌏");
335 /// assert_eq!(Some("🗻"), v.get(0..4));
337 /// // indices not on UTF-8 sequence boundaries
338 /// assert!(v.get(1..).is_none());
339 /// assert!(v.get(..8).is_none());
342 /// assert!(v.get(..42).is_none());
344 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
346 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
350 /// Returns a mutable subslice of `str`.
352 /// This is the non-panicking alternative to indexing the `str`. Returns
353 /// [`None`] whenever equivalent indexing operation would panic.
358 /// let mut v = String::from("hello");
359 /// // correct length
360 /// assert!(v.get_mut(0..5).is_some());
362 /// assert!(v.get_mut(..42).is_none());
363 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
365 /// assert_eq!("hello", v);
367 /// let s = v.get_mut(0..2);
368 /// let s = s.map(|s| {
369 /// s.make_ascii_uppercase();
372 /// assert_eq!(Some("HE"), s);
374 /// assert_eq!("HEllo", v);
376 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
378 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
382 /// Returns an unchecked subslice of `str`.
384 /// This is the unchecked alternative to indexing the `str`.
388 /// Callers of this function are responsible that these preconditions are
391 /// * The starting index must not exceed the ending index;
392 /// * Indexes must be within bounds of the original slice;
393 /// * Indexes must lie on UTF-8 sequence boundaries.
395 /// Failing that, the returned string slice may reference invalid memory or
396 /// violate the invariants communicated by the `str` type.
403 /// assert_eq!("🗻", v.get_unchecked(0..4));
404 /// assert_eq!("∈", v.get_unchecked(4..7));
405 /// assert_eq!("🌏", v.get_unchecked(7..11));
408 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
410 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
411 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
412 // the slice is dereferencable because `self` is a safe reference.
413 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
414 unsafe { &*i.get_unchecked(self) }
417 /// Returns a mutable, unchecked subslice of `str`.
419 /// This is the unchecked alternative to indexing the `str`.
423 /// Callers of this function are responsible that these preconditions are
426 /// * The starting index must not exceed the ending index;
427 /// * Indexes must be within bounds of the original slice;
428 /// * Indexes must lie on UTF-8 sequence boundaries.
430 /// Failing that, the returned string slice may reference invalid memory or
431 /// violate the invariants communicated by the `str` type.
436 /// let mut v = String::from("🗻∈🌏");
438 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
439 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
440 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
443 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
445 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
446 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
447 // the slice is dereferencable because `self` is a safe reference.
448 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
449 unsafe { &mut *i.get_unchecked_mut(self) }
452 /// Creates a string slice from another string slice, bypassing safety
455 /// This is generally not recommended, use with caution! For a safe
456 /// alternative see [`str`] and [`Index`].
458 /// [`Index`]: crate::ops::Index
460 /// This new slice goes from `begin` to `end`, including `begin` but
463 /// To get a mutable string slice instead, see the
464 /// [`slice_mut_unchecked`] method.
466 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
470 /// Callers of this function are responsible that three preconditions are
473 /// * `begin` must not exceed `end`.
474 /// * `begin` and `end` must be byte positions within the string slice.
475 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
482 /// let s = "Löwe 老虎 Léopard";
485 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
488 /// let s = "Hello, world!";
491 /// assert_eq!("world", s.slice_unchecked(7, 12));
494 #[stable(feature = "rust1", since = "1.0.0")]
495 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
497 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
498 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
499 // the slice is dereferencable because `self` is a safe reference.
500 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
501 unsafe { &*(begin..end).get_unchecked(self) }
504 /// Creates a string slice from another string slice, bypassing safety
506 /// This is generally not recommended, use with caution! For a safe
507 /// alternative see [`str`] and [`IndexMut`].
509 /// [`IndexMut`]: crate::ops::IndexMut
511 /// This new slice goes from `begin` to `end`, including `begin` but
514 /// To get an immutable string slice instead, see the
515 /// [`slice_unchecked`] method.
517 /// [`slice_unchecked`]: str::slice_unchecked
521 /// Callers of this function are responsible that three preconditions are
524 /// * `begin` must not exceed `end`.
525 /// * `begin` and `end` must be byte positions within the string slice.
526 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
527 #[stable(feature = "str_slice_mut", since = "1.5.0")]
528 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
530 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
531 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
532 // the slice is dereferencable because `self` is a safe reference.
533 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
534 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
537 /// Divide one string slice into two at an index.
539 /// The argument, `mid`, should be a byte offset from the start of the
540 /// string. It must also be on the boundary of a UTF-8 code point.
542 /// The two slices returned go from the start of the string slice to `mid`,
543 /// and from `mid` to the end of the string slice.
545 /// To get mutable string slices instead, see the [`split_at_mut`]
548 /// [`split_at_mut`]: str::split_at_mut
552 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
553 /// past the end of the last code point of the string slice.
560 /// let s = "Per Martin-Löf";
562 /// let (first, last) = s.split_at(3);
564 /// assert_eq!("Per", first);
565 /// assert_eq!(" Martin-Löf", last);
568 #[stable(feature = "str_split_at", since = "1.4.0")]
569 pub fn split_at(&self, mid: usize) -> (&str, &str) {
570 // is_char_boundary checks that the index is in [0, .len()]
571 if self.is_char_boundary(mid) {
572 // SAFETY: just checked that `mid` is on a char boundary.
573 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
575 slice_error_fail(self, 0, mid)
579 /// Divide one mutable string slice into two at an index.
581 /// The argument, `mid`, should be a byte offset from the start of the
582 /// string. It must also be on the boundary of a UTF-8 code point.
584 /// The two slices returned go from the start of the string slice to `mid`,
585 /// and from `mid` to the end of the string slice.
587 /// To get immutable string slices instead, see the [`split_at`] method.
589 /// [`split_at`]: str::split_at
593 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
594 /// past the end of the last code point of the string slice.
601 /// let mut s = "Per Martin-Löf".to_string();
603 /// let (first, last) = s.split_at_mut(3);
604 /// first.make_ascii_uppercase();
605 /// assert_eq!("PER", first);
606 /// assert_eq!(" Martin-Löf", last);
608 /// assert_eq!("PER Martin-Löf", s);
611 #[stable(feature = "str_split_at", since = "1.4.0")]
612 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
613 // is_char_boundary checks that the index is in [0, .len()]
614 if self.is_char_boundary(mid) {
615 let len = self.len();
616 let ptr = self.as_mut_ptr();
617 // SAFETY: just checked that `mid` is on a char boundary.
620 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
621 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
625 slice_error_fail(self, 0, mid)
629 /// Returns an iterator over the [`char`]s of a string slice.
631 /// As a string slice consists of valid UTF-8, we can iterate through a
632 /// string slice by [`char`]. This method returns such an iterator.
634 /// It's important to remember that [`char`] represents a Unicode Scalar
635 /// Value, and might not match your idea of what a 'character' is. Iteration
636 /// over grapheme clusters may be what you actually want. This functionality
637 /// is not provided by Rust's standard library, check crates.io instead.
644 /// let word = "goodbye";
646 /// let count = word.chars().count();
647 /// assert_eq!(7, count);
649 /// let mut chars = word.chars();
651 /// assert_eq!(Some('g'), chars.next());
652 /// assert_eq!(Some('o'), chars.next());
653 /// assert_eq!(Some('o'), chars.next());
654 /// assert_eq!(Some('d'), chars.next());
655 /// assert_eq!(Some('b'), chars.next());
656 /// assert_eq!(Some('y'), chars.next());
657 /// assert_eq!(Some('e'), chars.next());
659 /// assert_eq!(None, chars.next());
662 /// Remember, [`char`]s might not match your intuition about characters:
664 /// [`char`]: prim@char
669 /// let mut chars = y.chars();
671 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
672 /// assert_eq!(Some('\u{0306}'), chars.next());
674 /// assert_eq!(None, chars.next());
676 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn chars(&self) -> Chars<'_> {
679 Chars { iter: self.as_bytes().iter() }
682 /// Returns an iterator over the [`char`]s of a string slice, and their
685 /// As a string slice consists of valid UTF-8, we can iterate through a
686 /// string slice by [`char`]. This method returns an iterator of both
687 /// these [`char`]s, as well as their byte positions.
689 /// The iterator yields tuples. The position is first, the [`char`] is
697 /// let word = "goodbye";
699 /// let count = word.char_indices().count();
700 /// assert_eq!(7, count);
702 /// let mut char_indices = word.char_indices();
704 /// assert_eq!(Some((0, 'g')), char_indices.next());
705 /// assert_eq!(Some((1, 'o')), char_indices.next());
706 /// assert_eq!(Some((2, 'o')), char_indices.next());
707 /// assert_eq!(Some((3, 'd')), char_indices.next());
708 /// assert_eq!(Some((4, 'b')), char_indices.next());
709 /// assert_eq!(Some((5, 'y')), char_indices.next());
710 /// assert_eq!(Some((6, 'e')), char_indices.next());
712 /// assert_eq!(None, char_indices.next());
715 /// Remember, [`char`]s might not match your intuition about characters:
717 /// [`char`]: prim@char
720 /// let yes = "y̆es";
722 /// let mut char_indices = yes.char_indices();
724 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
725 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
727 /// // note the 3 here - the last character took up two bytes
728 /// assert_eq!(Some((3, 'e')), char_indices.next());
729 /// assert_eq!(Some((4, 's')), char_indices.next());
731 /// assert_eq!(None, char_indices.next());
733 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn char_indices(&self) -> CharIndices<'_> {
736 CharIndices { front_offset: 0, iter: self.chars() }
739 /// An iterator over the bytes of a string slice.
741 /// As a string slice consists of a sequence of bytes, we can iterate
742 /// through a string slice by byte. This method returns such an iterator.
749 /// let mut bytes = "bors".bytes();
751 /// assert_eq!(Some(b'b'), bytes.next());
752 /// assert_eq!(Some(b'o'), bytes.next());
753 /// assert_eq!(Some(b'r'), bytes.next());
754 /// assert_eq!(Some(b's'), bytes.next());
756 /// assert_eq!(None, bytes.next());
758 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn bytes(&self) -> Bytes<'_> {
761 Bytes(self.as_bytes().iter().copied())
764 /// Splits a string slice by whitespace.
766 /// The iterator returned will return string slices that are sub-slices of
767 /// the original string slice, separated by any amount of whitespace.
769 /// 'Whitespace' is defined according to the terms of the Unicode Derived
770 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
771 /// instead, use [`split_ascii_whitespace`].
773 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
780 /// let mut iter = "A few words".split_whitespace();
782 /// assert_eq!(Some("A"), iter.next());
783 /// assert_eq!(Some("few"), iter.next());
784 /// assert_eq!(Some("words"), iter.next());
786 /// assert_eq!(None, iter.next());
789 /// All kinds of whitespace are considered:
792 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
793 /// assert_eq!(Some("Mary"), iter.next());
794 /// assert_eq!(Some("had"), iter.next());
795 /// assert_eq!(Some("a"), iter.next());
796 /// assert_eq!(Some("little"), iter.next());
797 /// assert_eq!(Some("lamb"), iter.next());
799 /// assert_eq!(None, iter.next());
801 #[stable(feature = "split_whitespace", since = "1.1.0")]
803 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
804 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
807 /// Splits a string slice by ASCII whitespace.
809 /// The iterator returned will return string slices that are sub-slices of
810 /// the original string slice, separated by any amount of ASCII whitespace.
812 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
814 /// [`split_whitespace`]: str::split_whitespace
821 /// let mut iter = "A few words".split_ascii_whitespace();
823 /// assert_eq!(Some("A"), iter.next());
824 /// assert_eq!(Some("few"), iter.next());
825 /// assert_eq!(Some("words"), iter.next());
827 /// assert_eq!(None, iter.next());
830 /// All kinds of ASCII whitespace are considered:
833 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
834 /// assert_eq!(Some("Mary"), iter.next());
835 /// assert_eq!(Some("had"), iter.next());
836 /// assert_eq!(Some("a"), iter.next());
837 /// assert_eq!(Some("little"), iter.next());
838 /// assert_eq!(Some("lamb"), iter.next());
840 /// assert_eq!(None, iter.next());
842 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
844 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
846 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
847 SplitAsciiWhitespace { inner }
850 /// An iterator over the lines of a string, as string slices.
852 /// Lines are ended with either a newline (`\n`) or a carriage return with
853 /// a line feed (`\r\n`).
855 /// The final line ending is optional. A string that ends with a final line
856 /// ending will return the same lines as an otherwise identical string
857 /// without a final line ending.
864 /// let text = "foo\r\nbar\n\nbaz\n";
865 /// let mut lines = text.lines();
867 /// assert_eq!(Some("foo"), lines.next());
868 /// assert_eq!(Some("bar"), lines.next());
869 /// assert_eq!(Some(""), lines.next());
870 /// assert_eq!(Some("baz"), lines.next());
872 /// assert_eq!(None, lines.next());
875 /// The final line ending isn't required:
878 /// let text = "foo\nbar\n\r\nbaz";
879 /// let mut lines = text.lines();
881 /// assert_eq!(Some("foo"), lines.next());
882 /// assert_eq!(Some("bar"), lines.next());
883 /// assert_eq!(Some(""), lines.next());
884 /// assert_eq!(Some("baz"), lines.next());
886 /// assert_eq!(None, lines.next());
888 #[stable(feature = "rust1", since = "1.0.0")]
890 pub fn lines(&self) -> Lines<'_> {
891 Lines(self.split_terminator('\n').map(LinesAnyMap))
894 /// An iterator over the lines of a string.
895 #[stable(feature = "rust1", since = "1.0.0")]
896 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
899 pub fn lines_any(&self) -> LinesAny<'_> {
900 LinesAny(self.lines())
903 /// Returns an iterator of `u16` over the string encoded as UTF-16.
910 /// let text = "Zażółć gęślą jaźń";
912 /// let utf8_len = text.len();
913 /// let utf16_len = text.encode_utf16().count();
915 /// assert!(utf16_len <= utf8_len);
917 #[stable(feature = "encode_utf16", since = "1.8.0")]
918 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
919 EncodeUtf16 { chars: self.chars(), extra: 0 }
922 /// Returns `true` if the given pattern matches a sub-slice of
923 /// this string slice.
925 /// Returns `false` if it does not.
927 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
928 /// function or closure that determines if a character matches.
930 /// [`char`]: prim@char
931 /// [pattern]: self::pattern
938 /// let bananas = "bananas";
940 /// assert!(bananas.contains("nana"));
941 /// assert!(!bananas.contains("apples"));
943 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
946 pat.is_contained_in(self)
949 /// Returns `true` if the given pattern matches a prefix of this
952 /// Returns `false` if it does not.
954 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
955 /// function or closure that determines if a character matches.
957 /// [`char`]: prim@char
958 /// [pattern]: self::pattern
965 /// let bananas = "bananas";
967 /// assert!(bananas.starts_with("bana"));
968 /// assert!(!bananas.starts_with("nana"));
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
972 pat.is_prefix_of(self)
975 /// Returns `true` if the given pattern matches a suffix of this
978 /// Returns `false` if it does not.
980 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
981 /// function or closure that determines if a character matches.
983 /// [`char`]: prim@char
984 /// [pattern]: self::pattern
991 /// let bananas = "bananas";
993 /// assert!(bananas.ends_with("anas"));
994 /// assert!(!bananas.ends_with("nana"));
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
999 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1001 pat.is_suffix_of(self)
1004 /// Returns the byte index of the first character of this string slice that
1005 /// matches the pattern.
1007 /// Returns [`None`] if the pattern doesn't match.
1009 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1010 /// function or closure that determines if a character matches.
1012 /// [`char`]: prim@char
1013 /// [pattern]: self::pattern
1017 /// Simple patterns:
1020 /// let s = "Löwe 老虎 Léopard Gepardi";
1022 /// assert_eq!(s.find('L'), Some(0));
1023 /// assert_eq!(s.find('é'), Some(14));
1024 /// assert_eq!(s.find("pard"), Some(17));
1027 /// More complex patterns using point-free style and closures:
1030 /// let s = "Löwe 老虎 Léopard";
1032 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1033 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1034 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1035 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1038 /// Not finding the pattern:
1041 /// let s = "Löwe 老虎 Léopard";
1042 /// let x: &[_] = &['1', '2'];
1044 /// assert_eq!(s.find(x), None);
1046 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1049 pat.into_searcher(self).next_match().map(|(i, _)| i)
1052 /// Returns the byte index for the first character of the rightmost match of the pattern in
1053 /// this string slice.
1055 /// Returns [`None`] if the pattern doesn't match.
1057 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1058 /// function or closure that determines if a character matches.
1060 /// [`char`]: prim@char
1061 /// [pattern]: self::pattern
1065 /// Simple patterns:
1068 /// let s = "Löwe 老虎 Léopard Gepardi";
1070 /// assert_eq!(s.rfind('L'), Some(13));
1071 /// assert_eq!(s.rfind('é'), Some(14));
1072 /// assert_eq!(s.rfind("pard"), Some(24));
1075 /// More complex patterns with closures:
1078 /// let s = "Löwe 老虎 Léopard";
1080 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1081 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1084 /// Not finding the pattern:
1087 /// let s = "Löwe 老虎 Léopard";
1088 /// let x: &[_] = &['1', '2'];
1090 /// assert_eq!(s.rfind(x), None);
1092 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1096 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1098 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1101 /// An iterator over substrings of this string slice, separated by
1102 /// characters matched by a pattern.
1104 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1105 /// function or closure that determines if a character matches.
1107 /// [`char`]: prim@char
1108 /// [pattern]: self::pattern
1110 /// # Iterator behavior
1112 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1113 /// allows a reverse search and forward/reverse search yields the same
1114 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1116 /// If the pattern allows a reverse search but its results might differ
1117 /// from a forward search, the [`rsplit`] method can be used.
1119 /// [`rsplit`]: str::rsplit
1123 /// Simple patterns:
1126 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1127 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1129 /// let v: Vec<&str> = "".split('X').collect();
1130 /// assert_eq!(v, [""]);
1132 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1133 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1135 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1136 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1138 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1139 /// assert_eq!(v, ["abc", "def", "ghi"]);
1141 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1142 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1145 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1148 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1149 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1152 /// A more complex pattern, using a closure:
1155 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1156 /// assert_eq!(v, ["abc", "def", "ghi"]);
1159 /// If a string contains multiple contiguous separators, you will end up
1160 /// with empty strings in the output:
1163 /// let x = "||||a||b|c".to_string();
1164 /// let d: Vec<_> = x.split('|').collect();
1166 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1169 /// Contiguous separators are separated by the empty string.
1172 /// let x = "(///)".to_string();
1173 /// let d: Vec<_> = x.split('/').collect();
1175 /// assert_eq!(d, &["(", "", "", ")"]);
1178 /// Separators at the start or end of a string are neighbored
1179 /// by empty strings.
1182 /// let d: Vec<_> = "010".split("0").collect();
1183 /// assert_eq!(d, &["", "1", ""]);
1186 /// When the empty string is used as a separator, it separates
1187 /// every character in the string, along with the beginning
1188 /// and end of the string.
1191 /// let f: Vec<_> = "rust".split("").collect();
1192 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1195 /// Contiguous separators can lead to possibly surprising behavior
1196 /// when whitespace is used as the separator. This code is correct:
1199 /// let x = " a b c".to_string();
1200 /// let d: Vec<_> = x.split(' ').collect();
1202 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1205 /// It does _not_ give you:
1208 /// assert_eq!(d, &["a", "b", "c"]);
1211 /// Use [`split_whitespace`] for this behavior.
1213 /// [`split_whitespace`]: str::split_whitespace
1214 #[stable(feature = "rust1", since = "1.0.0")]
1216 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1217 Split(SplitInternal {
1220 matcher: pat.into_searcher(self),
1221 allow_trailing_empty: true,
1226 /// An iterator over substrings of this string slice, separated by
1227 /// characters matched by a pattern. Differs from the iterator produced by
1228 /// `split` in that `split_inclusive` leaves the matched part as the
1229 /// terminator of the substring.
1231 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1232 /// function or closure that determines if a character matches.
1234 /// [`char`]: prim@char
1235 /// [pattern]: self::pattern
1240 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1241 /// .split_inclusive('\n').collect();
1242 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1245 /// If the last element of the string is matched,
1246 /// that element will be considered the terminator of the preceding substring.
1247 /// That substring will be the last item returned by the iterator.
1250 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1251 /// .split_inclusive('\n').collect();
1252 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1254 #[stable(feature = "split_inclusive", since = "1.51.0")]
1256 pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1257 SplitInclusive(SplitInternal {
1260 matcher: pat.into_searcher(self),
1261 allow_trailing_empty: false,
1266 /// An iterator over substrings of the given string slice, separated by
1267 /// characters matched by a pattern and yielded in reverse order.
1269 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1270 /// function or closure that determines if a character matches.
1272 /// [`char`]: prim@char
1273 /// [pattern]: self::pattern
1275 /// # Iterator behavior
1277 /// The returned iterator requires that the pattern supports a reverse
1278 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1279 /// search yields the same elements.
1281 /// For iterating from the front, the [`split`] method can be used.
1283 /// [`split`]: str::split
1287 /// Simple patterns:
1290 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1291 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1293 /// let v: Vec<&str> = "".rsplit('X').collect();
1294 /// assert_eq!(v, [""]);
1296 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1297 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1299 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1300 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1303 /// A more complex pattern, using a closure:
1306 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1307 /// assert_eq!(v, ["ghi", "def", "abc"]);
1309 #[stable(feature = "rust1", since = "1.0.0")]
1311 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1313 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1315 RSplit(self.split(pat).0)
1318 /// An iterator over substrings of the given string slice, separated by
1319 /// characters matched by a pattern.
1321 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1322 /// function or closure that determines if a character matches.
1324 /// [`char`]: prim@char
1325 /// [pattern]: self::pattern
1327 /// Equivalent to [`split`], except that the trailing substring
1328 /// is skipped if empty.
1330 /// [`split`]: str::split
1332 /// This method can be used for string data that is _terminated_,
1333 /// rather than _separated_ by a pattern.
1335 /// # Iterator behavior
1337 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1338 /// allows a reverse search and forward/reverse search yields the same
1339 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1341 /// If the pattern allows a reverse search but its results might differ
1342 /// from a forward search, the [`rsplit_terminator`] method can be used.
1344 /// [`rsplit_terminator`]: str::rsplit_terminator
1351 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1352 /// assert_eq!(v, ["A", "B"]);
1354 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1355 /// assert_eq!(v, ["A", "", "B", ""]);
1357 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1360 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1363 /// An iterator over substrings of `self`, separated by characters
1364 /// matched by a pattern and yielded in reverse order.
1366 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1367 /// function or closure that determines if a character matches.
1369 /// [`char`]: prim@char
1370 /// [pattern]: self::pattern
1372 /// Equivalent to [`split`], except that the trailing substring is
1373 /// skipped if empty.
1375 /// [`split`]: str::split
1377 /// This method can be used for string data that is _terminated_,
1378 /// rather than _separated_ by a pattern.
1380 /// # Iterator behavior
1382 /// The returned iterator requires that the pattern supports a
1383 /// reverse search, and it will be double ended if a forward/reverse
1384 /// search yields the same elements.
1386 /// For iterating from the front, the [`split_terminator`] method can be
1389 /// [`split_terminator`]: str::split_terminator
1394 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1395 /// assert_eq!(v, ["B", "A"]);
1397 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1398 /// assert_eq!(v, ["", "B", "", "A"]);
1400 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1404 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1406 RSplitTerminator(self.split_terminator(pat).0)
1409 /// An iterator over substrings of the given string slice, separated by a
1410 /// pattern, restricted to returning at most `n` items.
1412 /// If `n` substrings are returned, the last substring (the `n`th substring)
1413 /// will contain the remainder of the string.
1415 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1416 /// function or closure that determines if a character matches.
1418 /// [`char`]: prim@char
1419 /// [pattern]: self::pattern
1421 /// # Iterator behavior
1423 /// The returned iterator will not be double ended, because it is
1424 /// not efficient to support.
1426 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1429 /// [`rsplitn`]: str::rsplitn
1433 /// Simple patterns:
1436 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1437 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1439 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1440 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1442 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1443 /// assert_eq!(v, ["abcXdef"]);
1445 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1446 /// assert_eq!(v, [""]);
1449 /// A more complex pattern, using a closure:
1452 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1453 /// assert_eq!(v, ["abc", "defXghi"]);
1455 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1458 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1461 /// An iterator over substrings of this string slice, separated by a
1462 /// pattern, starting from the end of the string, restricted to returning
1463 /// at most `n` items.
1465 /// If `n` substrings are returned, the last substring (the `n`th substring)
1466 /// will contain the remainder of the string.
1468 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1469 /// function or closure that determines if a character matches.
1471 /// [`char`]: prim@char
1472 /// [pattern]: self::pattern
1474 /// # Iterator behavior
1476 /// The returned iterator will not be double ended, because it is not
1477 /// efficient to support.
1479 /// For splitting from the front, the [`splitn`] method can be used.
1481 /// [`splitn`]: str::splitn
1485 /// Simple patterns:
1488 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1489 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1491 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1492 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1494 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1495 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1498 /// A more complex pattern, using a closure:
1501 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1502 /// assert_eq!(v, ["ghi", "abc1def"]);
1504 #[stable(feature = "rust1", since = "1.0.0")]
1506 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1508 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1510 RSplitN(self.splitn(n, pat).0)
1513 /// Splits the string on the first occurrence of the specified delimiter and
1514 /// returns prefix before delimiter and suffix after delimiter.
1519 /// assert_eq!("cfg".split_once('='), None);
1520 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1521 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1523 #[stable(feature = "str_split_once", since = "1.52.0")]
1525 pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1526 let (start, end) = delimiter.into_searcher(self).next_match()?;
1527 Some((&self[..start], &self[end..]))
1530 /// Splits the string on the last occurrence of the specified delimiter and
1531 /// returns prefix before delimiter and suffix after delimiter.
1536 /// assert_eq!("cfg".rsplit_once('='), None);
1537 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1538 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1540 #[stable(feature = "str_split_once", since = "1.52.0")]
1542 pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1544 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1546 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1547 Some((&self[..start], &self[end..]))
1550 /// An iterator over the disjoint matches of a pattern within the given string
1553 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1554 /// function or closure that determines if a character matches.
1556 /// [`char`]: prim@char
1557 /// [pattern]: self::pattern
1559 /// # Iterator behavior
1561 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1562 /// allows a reverse search and forward/reverse search yields the same
1563 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1565 /// If the pattern allows a reverse search but its results might differ
1566 /// from a forward search, the [`rmatches`] method can be used.
1568 /// [`rmatches`]: str::matches
1575 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1576 /// assert_eq!(v, ["abc", "abc", "abc"]);
1578 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1579 /// assert_eq!(v, ["1", "2", "3"]);
1581 #[stable(feature = "str_matches", since = "1.2.0")]
1583 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1584 Matches(MatchesInternal(pat.into_searcher(self)))
1587 /// An iterator over the disjoint matches of a pattern within this string slice,
1588 /// yielded in reverse order.
1590 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1591 /// function or closure that determines if a character matches.
1593 /// [`char`]: prim@char
1594 /// [pattern]: self::pattern
1596 /// # Iterator behavior
1598 /// The returned iterator requires that the pattern supports a reverse
1599 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1600 /// search yields the same elements.
1602 /// For iterating from the front, the [`matches`] method can be used.
1604 /// [`matches`]: str::matches
1611 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1612 /// assert_eq!(v, ["abc", "abc", "abc"]);
1614 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1615 /// assert_eq!(v, ["3", "2", "1"]);
1617 #[stable(feature = "str_matches", since = "1.2.0")]
1619 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1621 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1623 RMatches(self.matches(pat).0)
1626 /// An iterator over the disjoint matches of a pattern within this string
1627 /// slice as well as the index that the match starts at.
1629 /// For matches of `pat` within `self` that overlap, only the indices
1630 /// corresponding to the first match are returned.
1632 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1633 /// function or closure that determines if a character matches.
1635 /// [`char`]: prim@char
1636 /// [pattern]: self::pattern
1638 /// # Iterator behavior
1640 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1641 /// allows a reverse search and forward/reverse search yields the same
1642 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1644 /// If the pattern allows a reverse search but its results might differ
1645 /// from a forward search, the [`rmatch_indices`] method can be used.
1647 /// [`rmatch_indices`]: str::match_indices
1654 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1655 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1657 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1658 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1660 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1661 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1663 #[stable(feature = "str_match_indices", since = "1.5.0")]
1665 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1666 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1669 /// An iterator over the disjoint matches of a pattern within `self`,
1670 /// yielded in reverse order along with the index of the match.
1672 /// For matches of `pat` within `self` that overlap, only the indices
1673 /// corresponding to the last match are returned.
1675 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1676 /// function or closure that determines if a character matches.
1678 /// [`char`]: prim@char
1679 /// [pattern]: self::pattern
1681 /// # Iterator behavior
1683 /// The returned iterator requires that the pattern supports a reverse
1684 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1685 /// search yields the same elements.
1687 /// For iterating from the front, the [`match_indices`] method can be used.
1689 /// [`match_indices`]: str::match_indices
1696 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1697 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1699 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1700 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1702 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1703 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1705 #[stable(feature = "str_match_indices", since = "1.5.0")]
1707 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1709 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1711 RMatchIndices(self.match_indices(pat).0)
1714 /// Returns a string slice with leading and trailing whitespace removed.
1716 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1717 /// Core Property `White_Space`.
1724 /// let s = " Hello\tworld\t";
1726 /// assert_eq!("Hello\tworld", s.trim());
1729 #[must_use = "this returns the trimmed string as a slice, \
1730 without modifying the original"]
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 pub fn trim(&self) -> &str {
1733 self.trim_matches(|c: char| c.is_whitespace())
1736 /// Returns a string slice with leading whitespace removed.
1738 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1739 /// Core Property `White_Space`.
1741 /// # Text directionality
1743 /// A string is a sequence of bytes. `start` in this context means the first
1744 /// position of that byte string; for a left-to-right language like English or
1745 /// Russian, this will be left side, and for right-to-left languages like
1746 /// Arabic or Hebrew, this will be the right side.
1753 /// let s = " Hello\tworld\t";
1754 /// assert_eq!("Hello\tworld\t", s.trim_start());
1760 /// let s = " English ";
1761 /// assert!(Some('E') == s.trim_start().chars().next());
1763 /// let s = " עברית ";
1764 /// assert!(Some('ע') == s.trim_start().chars().next());
1767 #[must_use = "this returns the trimmed string as a new slice, \
1768 without modifying the original"]
1769 #[stable(feature = "trim_direction", since = "1.30.0")]
1770 pub fn trim_start(&self) -> &str {
1771 self.trim_start_matches(|c: char| c.is_whitespace())
1774 /// Returns a string slice with trailing whitespace removed.
1776 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1777 /// Core Property `White_Space`.
1779 /// # Text directionality
1781 /// A string is a sequence of bytes. `end` in this context means the last
1782 /// position of that byte string; for a left-to-right language like English or
1783 /// Russian, this will be right side, and for right-to-left languages like
1784 /// Arabic or Hebrew, this will be the left side.
1791 /// let s = " Hello\tworld\t";
1792 /// assert_eq!(" Hello\tworld", s.trim_end());
1798 /// let s = " English ";
1799 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1801 /// let s = " עברית ";
1802 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1805 #[must_use = "this returns the trimmed string as a new slice, \
1806 without modifying the original"]
1807 #[stable(feature = "trim_direction", since = "1.30.0")]
1808 pub fn trim_end(&self) -> &str {
1809 self.trim_end_matches(|c: char| c.is_whitespace())
1812 /// Returns a string slice with leading whitespace removed.
1814 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1815 /// Core Property `White_Space`.
1817 /// # Text directionality
1819 /// A string is a sequence of bytes. 'Left' in this context means the first
1820 /// position of that byte string; for a language like Arabic or Hebrew
1821 /// which are 'right to left' rather than 'left to right', this will be
1822 /// the _right_ side, not the left.
1829 /// let s = " Hello\tworld\t";
1831 /// assert_eq!("Hello\tworld\t", s.trim_left());
1837 /// let s = " English";
1838 /// assert!(Some('E') == s.trim_left().chars().next());
1840 /// let s = " עברית";
1841 /// assert!(Some('ע') == s.trim_left().chars().next());
1844 #[stable(feature = "rust1", since = "1.0.0")]
1847 reason = "superseded by `trim_start`",
1848 suggestion = "trim_start"
1850 pub fn trim_left(&self) -> &str {
1854 /// Returns a string slice with trailing whitespace removed.
1856 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1857 /// Core Property `White_Space`.
1859 /// # Text directionality
1861 /// A string is a sequence of bytes. 'Right' in this context means the last
1862 /// position of that byte string; for a language like Arabic or Hebrew
1863 /// which are 'right to left' rather than 'left to right', this will be
1864 /// the _left_ side, not the right.
1871 /// let s = " Hello\tworld\t";
1873 /// assert_eq!(" Hello\tworld", s.trim_right());
1879 /// let s = "English ";
1880 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1882 /// let s = "עברית ";
1883 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1886 #[stable(feature = "rust1", since = "1.0.0")]
1889 reason = "superseded by `trim_end`",
1890 suggestion = "trim_end"
1892 pub fn trim_right(&self) -> &str {
1896 /// Returns a string slice with all prefixes and suffixes that match a
1897 /// pattern repeatedly removed.
1899 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
1900 /// or closure that determines if a character matches.
1902 /// [`char`]: prim@char
1903 /// [pattern]: self::pattern
1907 /// Simple patterns:
1910 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1911 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1913 /// let x: &[_] = &['1', '2'];
1914 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1917 /// A more complex pattern, using a closure:
1920 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1922 #[must_use = "this returns the trimmed string as a new slice, \
1923 without modifying the original"]
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
1927 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
1931 let mut matcher = pat.into_searcher(self);
1932 if let Some((a, b)) = matcher.next_reject() {
1934 j = b; // Remember earliest known match, correct it below if
1935 // last match is different
1937 if let Some((_, b)) = matcher.next_reject_back() {
1940 // SAFETY: `Searcher` is known to return valid indices.
1941 unsafe { self.get_unchecked(i..j) }
1944 /// Returns a string slice with all prefixes that match a pattern
1945 /// repeatedly removed.
1947 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1948 /// function or closure that determines if a character matches.
1950 /// [`char`]: prim@char
1951 /// [pattern]: self::pattern
1953 /// # Text directionality
1955 /// A string is a sequence of bytes. `start` in this context means the first
1956 /// position of that byte string; for a left-to-right language like English or
1957 /// Russian, this will be left side, and for right-to-left languages like
1958 /// Arabic or Hebrew, this will be the right side.
1965 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
1966 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
1968 /// let x: &[_] = &['1', '2'];
1969 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1971 #[must_use = "this returns the trimmed string as a new slice, \
1972 without modifying the original"]
1973 #[stable(feature = "trim_direction", since = "1.30.0")]
1974 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
1975 let mut i = self.len();
1976 let mut matcher = pat.into_searcher(self);
1977 if let Some((a, _)) = matcher.next_reject() {
1980 // SAFETY: `Searcher` is known to return valid indices.
1981 unsafe { self.get_unchecked(i..self.len()) }
1984 /// Returns a string slice with the prefix removed.
1986 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
1987 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
1989 /// If the string does not start with `prefix`, returns `None`.
1991 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1992 /// function or closure that determines if a character matches.
1994 /// [`char`]: prim@char
1995 /// [pattern]: self::pattern
2000 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2001 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2002 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2004 #[must_use = "this returns the remaining substring as a new slice, \
2005 without modifying the original"]
2006 #[stable(feature = "str_strip", since = "1.45.0")]
2007 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2008 prefix.strip_prefix_of(self)
2011 /// Returns a string slice with the suffix removed.
2013 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2014 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2016 /// If the string does not end with `suffix`, returns `None`.
2018 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2019 /// function or closure that determines if a character matches.
2021 /// [`char`]: prim@char
2022 /// [pattern]: self::pattern
2027 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2028 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2029 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2031 #[must_use = "this returns the remaining substring as a new slice, \
2032 without modifying the original"]
2033 #[stable(feature = "str_strip", since = "1.45.0")]
2034 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2037 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2039 suffix.strip_suffix_of(self)
2042 /// Returns a string slice with all suffixes that match a pattern
2043 /// repeatedly removed.
2045 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2046 /// function or closure that determines if a character matches.
2048 /// [`char`]: prim@char
2049 /// [pattern]: self::pattern
2051 /// # Text directionality
2053 /// A string is a sequence of bytes. `end` in this context means the last
2054 /// position of that byte string; for a left-to-right language like English or
2055 /// Russian, this will be right side, and for right-to-left languages like
2056 /// Arabic or Hebrew, this will be the left side.
2060 /// Simple patterns:
2063 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2064 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2066 /// let x: &[_] = &['1', '2'];
2067 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2070 /// A more complex pattern, using a closure:
2073 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2075 #[must_use = "this returns the trimmed string as a new slice, \
2076 without modifying the original"]
2077 #[stable(feature = "trim_direction", since = "1.30.0")]
2078 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2080 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2083 let mut matcher = pat.into_searcher(self);
2084 if let Some((_, b)) = matcher.next_reject_back() {
2087 // SAFETY: `Searcher` is known to return valid indices.
2088 unsafe { self.get_unchecked(0..j) }
2091 /// Returns a string slice with all prefixes that match a pattern
2092 /// repeatedly removed.
2094 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2095 /// function or closure that determines if a character matches.
2097 /// [`char`]: prim@char
2098 /// [pattern]: self::pattern
2100 /// # Text directionality
2102 /// A string is a sequence of bytes. 'Left' in this context means the first
2103 /// position of that byte string; for a language like Arabic or Hebrew
2104 /// which are 'right to left' rather than 'left to right', this will be
2105 /// the _right_ side, not the left.
2112 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2113 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2115 /// let x: &[_] = &['1', '2'];
2116 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2118 #[stable(feature = "rust1", since = "1.0.0")]
2121 reason = "superseded by `trim_start_matches`",
2122 suggestion = "trim_start_matches"
2124 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2125 self.trim_start_matches(pat)
2128 /// Returns a string slice with all suffixes that match a pattern
2129 /// repeatedly removed.
2131 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2132 /// function or closure that determines if a character matches.
2134 /// [`char`]: prim@char
2135 /// [pattern]: self::pattern
2137 /// # Text directionality
2139 /// A string is a sequence of bytes. 'Right' in this context means the last
2140 /// position of that byte string; for a language like Arabic or Hebrew
2141 /// which are 'right to left' rather than 'left to right', this will be
2142 /// the _left_ side, not the right.
2146 /// Simple patterns:
2149 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2150 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2152 /// let x: &[_] = &['1', '2'];
2153 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2156 /// A more complex pattern, using a closure:
2159 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2161 #[stable(feature = "rust1", since = "1.0.0")]
2164 reason = "superseded by `trim_end_matches`",
2165 suggestion = "trim_end_matches"
2167 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2169 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2171 self.trim_end_matches(pat)
2174 /// Parses this string slice into another type.
2176 /// Because `parse` is so general, it can cause problems with type
2177 /// inference. As such, `parse` is one of the few times you'll see
2178 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2179 /// helps the inference algorithm understand specifically which type
2180 /// you're trying to parse into.
2182 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2187 /// Will return [`Err`] if it's not possible to parse this string slice into
2188 /// the desired type.
2190 /// [`Err`]: FromStr::Err
2197 /// let four: u32 = "4".parse().unwrap();
2199 /// assert_eq!(4, four);
2202 /// Using the 'turbofish' instead of annotating `four`:
2205 /// let four = "4".parse::<u32>();
2207 /// assert_eq!(Ok(4), four);
2210 /// Failing to parse:
2213 /// let nope = "j".parse::<u32>();
2215 /// assert!(nope.is_err());
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2220 FromStr::from_str(self)
2223 /// Checks if all characters in this string are within the ASCII range.
2228 /// let ascii = "hello!\n";
2229 /// let non_ascii = "Grüße, Jürgen ❤";
2231 /// assert!(ascii.is_ascii());
2232 /// assert!(!non_ascii.is_ascii());
2234 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2236 pub fn is_ascii(&self) -> bool {
2237 // We can treat each byte as character here: all multibyte characters
2238 // start with a byte that is not in the ascii range, so we will stop
2240 self.as_bytes().is_ascii()
2243 /// Checks that two strings are an ASCII case-insensitive match.
2245 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2246 /// but without allocating and copying temporaries.
2251 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2252 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2253 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2255 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2257 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2258 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2261 /// Converts this string to its ASCII upper case equivalent in-place.
2263 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2264 /// but non-ASCII letters are unchanged.
2266 /// To return a new uppercased value without modifying the existing one, use
2267 /// [`to_ascii_uppercase()`].
2269 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2274 /// let mut s = String::from("Grüße, Jürgen ❤");
2276 /// s.make_ascii_uppercase();
2278 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2280 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2282 pub fn make_ascii_uppercase(&mut self) {
2283 // SAFETY: safe because we transmute two types with the same layout.
2284 let me = unsafe { self.as_bytes_mut() };
2285 me.make_ascii_uppercase()
2288 /// Converts this string to its ASCII lower case equivalent in-place.
2290 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2291 /// but non-ASCII letters are unchanged.
2293 /// To return a new lowercased value without modifying the existing one, use
2294 /// [`to_ascii_lowercase()`].
2296 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2301 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2303 /// s.make_ascii_lowercase();
2305 /// assert_eq!("grÜße, jÜrgen ❤", s);
2307 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2309 pub fn make_ascii_lowercase(&mut self) {
2310 // SAFETY: safe because we transmute two types with the same layout.
2311 let me = unsafe { self.as_bytes_mut() };
2312 me.make_ascii_lowercase()
2315 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2317 /// Note: only extended grapheme codepoints that begin the string will be
2325 /// for c in "❤\n!".escape_debug() {
2326 /// print!("{}", c);
2331 /// Using `println!` directly:
2334 /// println!("{}", "❤\n!".escape_debug());
2338 /// Both are equivalent to:
2341 /// println!("❤\\n!");
2344 /// Using `to_string`:
2347 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2349 #[stable(feature = "str_escape", since = "1.34.0")]
2350 pub fn escape_debug(&self) -> EscapeDebug<'_> {
2351 let mut chars = self.chars();
2355 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2358 .chain(chars.flat_map(CharEscapeDebugContinue)),
2362 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2369 /// for c in "❤\n!".escape_default() {
2370 /// print!("{}", c);
2375 /// Using `println!` directly:
2378 /// println!("{}", "❤\n!".escape_default());
2382 /// Both are equivalent to:
2385 /// println!("\\u{{2764}}\\n!");
2388 /// Using `to_string`:
2391 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2393 #[stable(feature = "str_escape", since = "1.34.0")]
2394 pub fn escape_default(&self) -> EscapeDefault<'_> {
2395 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2398 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2405 /// for c in "❤\n!".escape_unicode() {
2406 /// print!("{}", c);
2411 /// Using `println!` directly:
2414 /// println!("{}", "❤\n!".escape_unicode());
2418 /// Both are equivalent to:
2421 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2424 /// Using `to_string`:
2427 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2429 #[stable(feature = "str_escape", since = "1.34.0")]
2430 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2431 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 impl AsRef<[u8]> for str {
2438 fn as_ref(&self) -> &[u8] {
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2445 impl const Default for &str {
2446 /// Creates an empty str
2448 fn default() -> Self {
2453 #[stable(feature = "default_mut_str", since = "1.28.0")]
2454 impl Default for &mut str {
2455 /// Creates an empty mutable str
2457 fn default() -> Self {
2458 // SAFETY: The empty string is valid UTF-8.
2459 unsafe { from_utf8_unchecked_mut(&mut []) }
2464 /// A nameable, cloneable fn type
2466 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2468 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2473 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2474 c.escape_debug_ext(EscapeDebugExtArgs {
2475 escape_grapheme_extended: false,
2476 escape_single_quote: true,
2477 escape_double_quote: true
2482 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2486 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2491 struct IsWhitespace impl Fn = |c: char| -> bool {
2496 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2497 byte.is_ascii_whitespace()
2501 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2506 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2511 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2513 unsafe { from_utf8_unchecked(bytes) }