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")]
145 pub const fn len(&self) -> usize {
146 self.as_bytes().len()
149 /// Returns `true` if `self` has a length of zero bytes.
157 /// assert!(s.is_empty());
159 /// let s = "not empty";
160 /// 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")]
166 pub const fn is_empty(&self) -> bool {
170 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
171 /// sequence or the end of the string.
173 /// The start and end of the string (when `index == self.len()`) are
174 /// considered to be boundaries.
176 /// Returns `false` if `index` is greater than `self.len()`.
181 /// let s = "Löwe 老虎 Léopard";
182 /// assert!(s.is_char_boundary(0));
184 /// assert!(s.is_char_boundary(6));
185 /// assert!(s.is_char_boundary(s.len()));
187 /// // second byte of `ö`
188 /// assert!(!s.is_char_boundary(2));
190 /// // third byte of `老`
191 /// assert!(!s.is_char_boundary(8));
194 #[stable(feature = "is_char_boundary", since = "1.9.0")]
196 pub fn is_char_boundary(&self, index: usize) -> bool {
198 // Test for 0 explicitly so that it can optimize out the check
199 // easily and skip reading string data for that case.
200 // Note that optimizing `self.get(..index)` relies on this.
205 match self.as_bytes().get(index) {
206 // For `None` we have two options:
208 // - index == self.len()
209 // Empty strings are valid, so return true
210 // - index > self.len()
211 // In this case return false
213 // The check is placed exactly here, because it improves generated
214 // code on higher opt-levels. See PR #84751 for more details.
215 None => index == self.len(),
217 // This is bit magic equivalent to: b < 128 || b >= 192
218 Some(&b) => (b as i8) >= -0x40,
222 /// Converts a string slice to a byte slice. To convert the byte slice back
223 /// into a string slice, use the [`from_utf8`] function.
230 /// let bytes = "bors".as_bytes();
231 /// assert_eq!(b"bors", bytes);
233 #[stable(feature = "rust1", since = "1.0.0")]
234 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
237 #[allow(unused_attributes)]
238 pub const fn as_bytes(&self) -> &[u8] {
239 // SAFETY: const sound because we transmute two types with the same layout
240 unsafe { mem::transmute(self) }
243 /// Converts a mutable string slice to a mutable byte slice.
247 /// The caller must ensure that the content of the slice is valid UTF-8
248 /// before the borrow ends and the underlying `str` is used.
250 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
257 /// let mut s = String::from("Hello");
258 /// let bytes = unsafe { s.as_bytes_mut() };
260 /// assert_eq!(b"Hello", bytes);
266 /// let mut s = String::from("🗻∈🌏");
269 /// let bytes = s.as_bytes_mut();
277 /// assert_eq!("🍔∈🌏", s);
279 #[stable(feature = "str_mut_extras", since = "1.20.0")]
282 pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
283 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
284 // has the same layout as `&[u8]` (only libstd can make this guarantee).
285 // The pointer dereference is safe since it comes from a mutable reference which
286 // is guaranteed to be valid for writes.
287 unsafe { &mut *(self as *mut str as *mut [u8]) }
290 /// Converts a string slice to a raw pointer.
292 /// As string slices are a slice of bytes, the raw pointer points to a
293 /// [`u8`]. This pointer will be pointing to the first byte of the string
296 /// The caller must ensure that the returned pointer is never written to.
297 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
299 /// [`as_mut_ptr`]: str::as_mut_ptr
307 /// let ptr = s.as_ptr();
309 #[stable(feature = "rust1", since = "1.0.0")]
310 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
313 pub const fn as_ptr(&self) -> *const u8 {
314 self as *const str as *const u8
317 /// Converts a mutable string slice to a raw pointer.
319 /// As string slices are a slice of bytes, the raw pointer points to a
320 /// [`u8`]. This pointer will be pointing to the first byte of the string
323 /// It is your responsibility to make sure that the string slice only gets
324 /// modified in a way that it remains valid UTF-8.
325 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
328 pub fn as_mut_ptr(&mut self) -> *mut u8 {
329 self as *mut str as *mut u8
332 /// Returns a subslice of `str`.
334 /// This is the non-panicking alternative to indexing the `str`. Returns
335 /// [`None`] whenever equivalent indexing operation would panic.
340 /// let v = String::from("🗻∈🌏");
342 /// assert_eq!(Some("🗻"), v.get(0..4));
344 /// // indices not on UTF-8 sequence boundaries
345 /// assert!(v.get(1..).is_none());
346 /// assert!(v.get(..8).is_none());
349 /// assert!(v.get(..42).is_none());
351 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
353 pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
357 /// Returns a mutable subslice of `str`.
359 /// This is the non-panicking alternative to indexing the `str`. Returns
360 /// [`None`] whenever equivalent indexing operation would panic.
365 /// let mut v = String::from("hello");
366 /// // correct length
367 /// assert!(v.get_mut(0..5).is_some());
369 /// assert!(v.get_mut(..42).is_none());
370 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
372 /// assert_eq!("hello", v);
374 /// let s = v.get_mut(0..2);
375 /// let s = s.map(|s| {
376 /// s.make_ascii_uppercase();
379 /// assert_eq!(Some("HE"), s);
381 /// assert_eq!("HEllo", v);
383 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
385 pub fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
389 /// Returns an unchecked subslice of `str`.
391 /// This is the unchecked alternative to indexing the `str`.
395 /// Callers of this function are responsible that these preconditions are
398 /// * The starting index must not exceed the ending index;
399 /// * Indexes must be within bounds of the original slice;
400 /// * Indexes must lie on UTF-8 sequence boundaries.
402 /// Failing that, the returned string slice may reference invalid memory or
403 /// violate the invariants communicated by the `str` type.
410 /// assert_eq!("🗻", v.get_unchecked(0..4));
411 /// assert_eq!("∈", v.get_unchecked(4..7));
412 /// assert_eq!("🌏", v.get_unchecked(7..11));
415 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
417 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
418 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
419 // the slice is dereferenceable because `self` is a safe reference.
420 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
421 unsafe { &*i.get_unchecked(self) }
424 /// Returns a mutable, unchecked subslice of `str`.
426 /// This is the unchecked alternative to indexing the `str`.
430 /// Callers of this function are responsible that these preconditions are
433 /// * The starting index must not exceed the ending index;
434 /// * Indexes must be within bounds of the original slice;
435 /// * Indexes must lie on UTF-8 sequence boundaries.
437 /// Failing that, the returned string slice may reference invalid memory or
438 /// violate the invariants communicated by the `str` type.
443 /// let mut v = String::from("🗻∈🌏");
445 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
446 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
447 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
450 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
452 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
453 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
454 // the slice is dereferenceable because `self` is a safe reference.
455 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
456 unsafe { &mut *i.get_unchecked_mut(self) }
459 /// Creates a string slice from another string slice, bypassing safety
462 /// This is generally not recommended, use with caution! For a safe
463 /// alternative see [`str`] and [`Index`].
465 /// [`Index`]: crate::ops::Index
467 /// This new slice goes from `begin` to `end`, including `begin` but
470 /// To get a mutable string slice instead, see the
471 /// [`slice_mut_unchecked`] method.
473 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
477 /// Callers of this function are responsible that three preconditions are
480 /// * `begin` must not exceed `end`.
481 /// * `begin` and `end` must be byte positions within the string slice.
482 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
489 /// let s = "Löwe 老虎 Léopard";
492 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
495 /// let s = "Hello, world!";
498 /// assert_eq!("world", s.slice_unchecked(7, 12));
501 #[stable(feature = "rust1", since = "1.0.0")]
502 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")]
505 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
506 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
507 // the slice is dereferenceable because `self` is a safe reference.
508 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
509 unsafe { &*(begin..end).get_unchecked(self) }
512 /// Creates a string slice from another string slice, bypassing safety
514 /// This is generally not recommended, use with caution! For a safe
515 /// alternative see [`str`] and [`IndexMut`].
517 /// [`IndexMut`]: crate::ops::IndexMut
519 /// This new slice goes from `begin` to `end`, including `begin` but
522 /// To get an immutable string slice instead, see the
523 /// [`slice_unchecked`] method.
525 /// [`slice_unchecked`]: str::slice_unchecked
529 /// Callers of this function are responsible that three preconditions are
532 /// * `begin` must not exceed `end`.
533 /// * `begin` and `end` must be byte positions within the string slice.
534 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
535 #[stable(feature = "str_slice_mut", since = "1.5.0")]
536 #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")]
538 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
539 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
540 // the slice is dereferenceable because `self` is a safe reference.
541 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
542 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
545 /// Divide one string slice into two at an index.
547 /// The argument, `mid`, should be a byte offset from the start of the
548 /// string. It must also be on the boundary of a UTF-8 code point.
550 /// The two slices returned go from the start of the string slice to `mid`,
551 /// and from `mid` to the end of the string slice.
553 /// To get mutable string slices instead, see the [`split_at_mut`]
556 /// [`split_at_mut`]: str::split_at_mut
560 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
561 /// past the end of the last code point of the string slice.
568 /// let s = "Per Martin-Löf";
570 /// let (first, last) = s.split_at(3);
572 /// assert_eq!("Per", first);
573 /// assert_eq!(" Martin-Löf", last);
577 #[stable(feature = "str_split_at", since = "1.4.0")]
578 pub fn split_at(&self, mid: usize) -> (&str, &str) {
579 // is_char_boundary checks that the index is in [0, .len()]
580 if self.is_char_boundary(mid) {
581 // SAFETY: just checked that `mid` is on a char boundary.
582 unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) }
584 slice_error_fail(self, 0, mid)
588 /// Divide one mutable string slice into two at an index.
590 /// The argument, `mid`, should be a byte offset from the start of the
591 /// string. It must also be on the boundary of a UTF-8 code point.
593 /// The two slices returned go from the start of the string slice to `mid`,
594 /// and from `mid` to the end of the string slice.
596 /// To get immutable string slices instead, see the [`split_at`] method.
598 /// [`split_at`]: str::split_at
602 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is
603 /// past the end of the last code point of the string slice.
610 /// let mut s = "Per Martin-Löf".to_string();
612 /// let (first, last) = s.split_at_mut(3);
613 /// first.make_ascii_uppercase();
614 /// assert_eq!("PER", first);
615 /// assert_eq!(" Martin-Löf", last);
617 /// assert_eq!("PER Martin-Löf", s);
621 #[stable(feature = "str_split_at", since = "1.4.0")]
622 pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
623 // is_char_boundary checks that the index is in [0, .len()]
624 if self.is_char_boundary(mid) {
625 let len = self.len();
626 let ptr = self.as_mut_ptr();
627 // SAFETY: just checked that `mid` is on a char boundary.
630 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
631 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
635 slice_error_fail(self, 0, mid)
639 /// Returns an iterator over the [`char`]s of a string slice.
641 /// As a string slice consists of valid UTF-8, we can iterate through a
642 /// string slice by [`char`]. This method returns such an iterator.
644 /// It's important to remember that [`char`] represents a Unicode Scalar
645 /// Value, and might not match your idea of what a 'character' is. Iteration
646 /// over grapheme clusters may be what you actually want. This functionality
647 /// is not provided by Rust's standard library, check crates.io instead.
654 /// let word = "goodbye";
656 /// let count = word.chars().count();
657 /// assert_eq!(7, count);
659 /// let mut chars = word.chars();
661 /// assert_eq!(Some('g'), chars.next());
662 /// assert_eq!(Some('o'), chars.next());
663 /// assert_eq!(Some('o'), chars.next());
664 /// assert_eq!(Some('d'), chars.next());
665 /// assert_eq!(Some('b'), chars.next());
666 /// assert_eq!(Some('y'), chars.next());
667 /// assert_eq!(Some('e'), chars.next());
669 /// assert_eq!(None, chars.next());
672 /// Remember, [`char`]s might not match your intuition about characters:
674 /// [`char`]: prim@char
679 /// let mut chars = y.chars();
681 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
682 /// assert_eq!(Some('\u{0306}'), chars.next());
684 /// assert_eq!(None, chars.next());
686 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn chars(&self) -> Chars<'_> {
689 Chars { iter: self.as_bytes().iter() }
692 /// Returns an iterator over the [`char`]s of a string slice, and their
695 /// As a string slice consists of valid UTF-8, we can iterate through a
696 /// string slice by [`char`]. This method returns an iterator of both
697 /// these [`char`]s, as well as their byte positions.
699 /// The iterator yields tuples. The position is first, the [`char`] is
707 /// let word = "goodbye";
709 /// let count = word.char_indices().count();
710 /// assert_eq!(7, count);
712 /// let mut char_indices = word.char_indices();
714 /// assert_eq!(Some((0, 'g')), char_indices.next());
715 /// assert_eq!(Some((1, 'o')), char_indices.next());
716 /// assert_eq!(Some((2, 'o')), char_indices.next());
717 /// assert_eq!(Some((3, 'd')), char_indices.next());
718 /// assert_eq!(Some((4, 'b')), char_indices.next());
719 /// assert_eq!(Some((5, 'y')), char_indices.next());
720 /// assert_eq!(Some((6, 'e')), char_indices.next());
722 /// assert_eq!(None, char_indices.next());
725 /// Remember, [`char`]s might not match your intuition about characters:
727 /// [`char`]: prim@char
730 /// let yes = "y̆es";
732 /// let mut char_indices = yes.char_indices();
734 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
735 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
737 /// // note the 3 here - the last character took up two bytes
738 /// assert_eq!(Some((3, 'e')), char_indices.next());
739 /// assert_eq!(Some((4, 's')), char_indices.next());
741 /// assert_eq!(None, char_indices.next());
743 #[stable(feature = "rust1", since = "1.0.0")]
745 pub fn char_indices(&self) -> CharIndices<'_> {
746 CharIndices { front_offset: 0, iter: self.chars() }
749 /// An iterator over the bytes of a string slice.
751 /// As a string slice consists of a sequence of bytes, we can iterate
752 /// through a string slice by byte. This method returns such an iterator.
759 /// let mut bytes = "bors".bytes();
761 /// assert_eq!(Some(b'b'), bytes.next());
762 /// assert_eq!(Some(b'o'), bytes.next());
763 /// assert_eq!(Some(b'r'), bytes.next());
764 /// assert_eq!(Some(b's'), bytes.next());
766 /// assert_eq!(None, bytes.next());
768 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn bytes(&self) -> Bytes<'_> {
771 Bytes(self.as_bytes().iter().copied())
774 /// Splits a string slice by whitespace.
776 /// The iterator returned will return string slices that are sub-slices of
777 /// the original string slice, separated by any amount of whitespace.
779 /// 'Whitespace' is defined according to the terms of the Unicode Derived
780 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
781 /// instead, use [`split_ascii_whitespace`].
783 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
790 /// let mut iter = "A few words".split_whitespace();
792 /// assert_eq!(Some("A"), iter.next());
793 /// assert_eq!(Some("few"), iter.next());
794 /// assert_eq!(Some("words"), iter.next());
796 /// assert_eq!(None, iter.next());
799 /// All kinds of whitespace are considered:
802 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
803 /// assert_eq!(Some("Mary"), iter.next());
804 /// assert_eq!(Some("had"), iter.next());
805 /// assert_eq!(Some("a"), iter.next());
806 /// assert_eq!(Some("little"), iter.next());
807 /// assert_eq!(Some("lamb"), iter.next());
809 /// assert_eq!(None, iter.next());
811 #[must_use = "this returns the split string as an iterator, \
812 without modifying the original"]
813 #[stable(feature = "split_whitespace", since = "1.1.0")]
815 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
816 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
819 /// Splits a string slice by ASCII whitespace.
821 /// The iterator returned will return string slices that are sub-slices of
822 /// the original string slice, separated by any amount of ASCII whitespace.
824 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
826 /// [`split_whitespace`]: str::split_whitespace
833 /// let mut iter = "A few words".split_ascii_whitespace();
835 /// assert_eq!(Some("A"), iter.next());
836 /// assert_eq!(Some("few"), iter.next());
837 /// assert_eq!(Some("words"), iter.next());
839 /// assert_eq!(None, iter.next());
842 /// All kinds of ASCII whitespace are considered:
845 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
846 /// assert_eq!(Some("Mary"), iter.next());
847 /// assert_eq!(Some("had"), iter.next());
848 /// assert_eq!(Some("a"), iter.next());
849 /// assert_eq!(Some("little"), iter.next());
850 /// assert_eq!(Some("lamb"), iter.next());
852 /// assert_eq!(None, iter.next());
854 #[must_use = "this returns the split string as an iterator, \
855 without modifying the original"]
856 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
858 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
860 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
861 SplitAsciiWhitespace { inner }
864 /// An iterator over the lines of a string, as string slices.
866 /// Lines are ended with either a newline (`\n`) or a carriage return with
867 /// a line feed (`\r\n`).
869 /// The final line ending is optional. A string that ends with a final line
870 /// ending will return the same lines as an otherwise identical string
871 /// without a final line ending.
878 /// let text = "foo\r\nbar\n\nbaz\n";
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());
889 /// The final line ending isn't required:
892 /// let text = "foo\nbar\n\r\nbaz";
893 /// let mut lines = text.lines();
895 /// assert_eq!(Some("foo"), lines.next());
896 /// assert_eq!(Some("bar"), lines.next());
897 /// assert_eq!(Some(""), lines.next());
898 /// assert_eq!(Some("baz"), lines.next());
900 /// assert_eq!(None, lines.next());
902 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn lines(&self) -> Lines<'_> {
905 Lines(self.split_terminator('\n').map(LinesAnyMap))
908 /// An iterator over the lines of a string.
909 #[stable(feature = "rust1", since = "1.0.0")]
910 #[rustc_deprecated(since = "1.4.0", reason = "use lines() instead now")]
913 pub fn lines_any(&self) -> LinesAny<'_> {
914 LinesAny(self.lines())
917 /// Returns an iterator of `u16` over the string encoded as UTF-16.
924 /// let text = "Zażółć gęślą jaźń";
926 /// let utf8_len = text.len();
927 /// let utf16_len = text.encode_utf16().count();
929 /// assert!(utf16_len <= utf8_len);
931 #[must_use = "this returns the encoded string as an iterator, \
932 without modifying the original"]
933 #[stable(feature = "encode_utf16", since = "1.8.0")]
934 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
935 EncodeUtf16 { chars: self.chars(), extra: 0 }
938 /// Returns `true` if the given pattern matches a sub-slice of
939 /// this string slice.
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.contains("nana"));
957 /// assert!(!bananas.contains("apples"));
959 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
962 pat.is_contained_in(self)
965 /// Returns `true` if the given pattern matches a prefix of this
968 /// Returns `false` if it does not.
970 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
971 /// function or closure that determines if a character matches.
973 /// [`char`]: prim@char
974 /// [pattern]: self::pattern
981 /// let bananas = "bananas";
983 /// assert!(bananas.starts_with("bana"));
984 /// assert!(!bananas.starts_with("nana"));
986 #[stable(feature = "rust1", since = "1.0.0")]
987 pub fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
988 pat.is_prefix_of(self)
991 /// Returns `true` if the given pattern matches a suffix of this
994 /// Returns `false` if it does not.
996 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
997 /// function or closure that determines if a character matches.
999 /// [`char`]: prim@char
1000 /// [pattern]: self::pattern
1007 /// let bananas = "bananas";
1009 /// assert!(bananas.ends_with("anas"));
1010 /// assert!(!bananas.ends_with("nana"));
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub fn ends_with<'a, P>(&'a self, pat: P) -> bool
1015 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1017 pat.is_suffix_of(self)
1020 /// Returns the byte index of the first character of this string slice that
1021 /// matches the pattern.
1023 /// Returns [`None`] if the pattern doesn't match.
1025 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1026 /// function or closure that determines if a character matches.
1028 /// [`char`]: prim@char
1029 /// [pattern]: self::pattern
1033 /// Simple patterns:
1036 /// let s = "Löwe 老虎 Léopard Gepardi";
1038 /// assert_eq!(s.find('L'), Some(0));
1039 /// assert_eq!(s.find('é'), Some(14));
1040 /// assert_eq!(s.find("pard"), Some(17));
1043 /// More complex patterns using point-free style and closures:
1046 /// let s = "Löwe 老虎 Léopard";
1048 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1049 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1050 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1051 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1054 /// Not finding the pattern:
1057 /// let s = "Löwe 老虎 Léopard";
1058 /// let x: &[_] = &['1', '2'];
1060 /// assert_eq!(s.find(x), None);
1062 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
1065 pat.into_searcher(self).next_match().map(|(i, _)| i)
1068 /// Returns the byte index for the first character of the rightmost match of the pattern in
1069 /// this string slice.
1071 /// Returns [`None`] if the pattern doesn't match.
1073 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1074 /// function or closure that determines if a character matches.
1076 /// [`char`]: prim@char
1077 /// [pattern]: self::pattern
1081 /// Simple patterns:
1084 /// let s = "Löwe 老虎 Léopard Gepardi";
1086 /// assert_eq!(s.rfind('L'), Some(13));
1087 /// assert_eq!(s.rfind('é'), Some(14));
1088 /// assert_eq!(s.rfind("pard"), Some(24));
1091 /// More complex patterns with closures:
1094 /// let s = "Löwe 老虎 Léopard";
1096 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1097 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1100 /// Not finding the pattern:
1103 /// let s = "Löwe 老虎 Léopard";
1104 /// let x: &[_] = &['1', '2'];
1106 /// assert_eq!(s.rfind(x), None);
1108 #[stable(feature = "rust1", since = "1.0.0")]
1110 pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize>
1112 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1114 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1117 /// An iterator over substrings of this string slice, separated by
1118 /// characters matched by a pattern.
1120 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1121 /// function or closure that determines if a character matches.
1123 /// [`char`]: prim@char
1124 /// [pattern]: self::pattern
1126 /// # Iterator behavior
1128 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1129 /// allows a reverse search and forward/reverse search yields the same
1130 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1132 /// If the pattern allows a reverse search but its results might differ
1133 /// from a forward search, the [`rsplit`] method can be used.
1135 /// [`rsplit`]: str::rsplit
1139 /// Simple patterns:
1142 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1143 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1145 /// let v: Vec<&str> = "".split('X').collect();
1146 /// assert_eq!(v, [""]);
1148 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1149 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1151 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1152 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1154 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1155 /// assert_eq!(v, ["abc", "def", "ghi"]);
1157 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1158 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1161 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1164 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1165 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1168 /// A more complex pattern, using a closure:
1171 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1172 /// assert_eq!(v, ["abc", "def", "ghi"]);
1175 /// If a string contains multiple contiguous separators, you will end up
1176 /// with empty strings in the output:
1179 /// let x = "||||a||b|c".to_string();
1180 /// let d: Vec<_> = x.split('|').collect();
1182 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1185 /// Contiguous separators are separated by the empty string.
1188 /// let x = "(///)".to_string();
1189 /// let d: Vec<_> = x.split('/').collect();
1191 /// assert_eq!(d, &["(", "", "", ")"]);
1194 /// Separators at the start or end of a string are neighbored
1195 /// by empty strings.
1198 /// let d: Vec<_> = "010".split("0").collect();
1199 /// assert_eq!(d, &["", "1", ""]);
1202 /// When the empty string is used as a separator, it separates
1203 /// every character in the string, along with the beginning
1204 /// and end of the string.
1207 /// let f: Vec<_> = "rust".split("").collect();
1208 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1211 /// Contiguous separators can lead to possibly surprising behavior
1212 /// when whitespace is used as the separator. This code is correct:
1215 /// let x = " a b c".to_string();
1216 /// let d: Vec<_> = x.split(' ').collect();
1218 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1221 /// It does _not_ give you:
1224 /// assert_eq!(d, &["a", "b", "c"]);
1227 /// Use [`split_whitespace`] for this behavior.
1229 /// [`split_whitespace`]: str::split_whitespace
1230 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
1233 Split(SplitInternal {
1236 matcher: pat.into_searcher(self),
1237 allow_trailing_empty: true,
1242 /// An iterator over substrings of this string slice, separated by
1243 /// characters matched by a pattern. Differs from the iterator produced by
1244 /// `split` in that `split_inclusive` leaves the matched part as the
1245 /// terminator of the substring.
1247 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1248 /// function or closure that determines if a character matches.
1250 /// [`char`]: prim@char
1251 /// [pattern]: self::pattern
1256 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1257 /// .split_inclusive('\n').collect();
1258 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1261 /// If the last element of the string is matched,
1262 /// that element will be considered the terminator of the preceding substring.
1263 /// That substring will be the last item returned by the iterator.
1266 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1267 /// .split_inclusive('\n').collect();
1268 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1270 #[stable(feature = "split_inclusive", since = "1.51.0")]
1272 pub fn split_inclusive<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitInclusive<'a, P> {
1273 SplitInclusive(SplitInternal {
1276 matcher: pat.into_searcher(self),
1277 allow_trailing_empty: false,
1282 /// An iterator over substrings of the given string slice, separated by
1283 /// characters matched by a pattern and yielded in reverse order.
1285 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1286 /// function or closure that determines if a character matches.
1288 /// [`char`]: prim@char
1289 /// [pattern]: self::pattern
1291 /// # Iterator behavior
1293 /// The returned iterator requires that the pattern supports a reverse
1294 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1295 /// search yields the same elements.
1297 /// For iterating from the front, the [`split`] method can be used.
1299 /// [`split`]: str::split
1303 /// Simple patterns:
1306 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1307 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1309 /// let v: Vec<&str> = "".rsplit('X').collect();
1310 /// assert_eq!(v, [""]);
1312 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1313 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1315 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1316 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1319 /// A more complex pattern, using a closure:
1322 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1323 /// assert_eq!(v, ["ghi", "def", "abc"]);
1325 #[stable(feature = "rust1", since = "1.0.0")]
1327 pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P>
1329 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1331 RSplit(self.split(pat).0)
1334 /// An iterator over substrings of the given string slice, separated by
1335 /// characters matched by a pattern.
1337 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1338 /// function or closure that determines if a character matches.
1340 /// [`char`]: prim@char
1341 /// [pattern]: self::pattern
1343 /// Equivalent to [`split`], except that the trailing substring
1344 /// is skipped if empty.
1346 /// [`split`]: str::split
1348 /// This method can be used for string data that is _terminated_,
1349 /// rather than _separated_ by a pattern.
1351 /// # Iterator behavior
1353 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1354 /// allows a reverse search and forward/reverse search yields the same
1355 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1357 /// If the pattern allows a reverse search but its results might differ
1358 /// from a forward search, the [`rsplit_terminator`] method can be used.
1360 /// [`rsplit_terminator`]: str::rsplit_terminator
1367 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1368 /// assert_eq!(v, ["A", "B"]);
1370 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1371 /// assert_eq!(v, ["A", "", "B", ""]);
1373 /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1374 /// assert_eq!(v, ["A", "B", "C", "D"]);
1376 #[stable(feature = "rust1", since = "1.0.0")]
1378 pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
1379 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1382 /// An iterator over substrings of `self`, separated by characters
1383 /// matched by a pattern and yielded in reverse order.
1385 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1386 /// function or closure that determines if a character matches.
1388 /// [`char`]: prim@char
1389 /// [pattern]: self::pattern
1391 /// Equivalent to [`split`], except that the trailing substring is
1392 /// skipped if empty.
1394 /// [`split`]: str::split
1396 /// This method can be used for string data that is _terminated_,
1397 /// rather than _separated_ by a pattern.
1399 /// # Iterator behavior
1401 /// The returned iterator requires that the pattern supports a
1402 /// reverse search, and it will be double ended if a forward/reverse
1403 /// search yields the same elements.
1405 /// For iterating from the front, the [`split_terminator`] method can be
1408 /// [`split_terminator`]: str::split_terminator
1413 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1414 /// assert_eq!(v, ["B", "A"]);
1416 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1417 /// assert_eq!(v, ["", "B", "", "A"]);
1419 /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1420 /// assert_eq!(v, ["D", "C", "B", "A"]);
1422 #[stable(feature = "rust1", since = "1.0.0")]
1424 pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P>
1426 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1428 RSplitTerminator(self.split_terminator(pat).0)
1431 /// An iterator over substrings of the given string slice, separated by a
1432 /// pattern, restricted to returning at most `n` items.
1434 /// If `n` substrings are returned, the last substring (the `n`th substring)
1435 /// will contain the remainder of the string.
1437 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1438 /// function or closure that determines if a character matches.
1440 /// [`char`]: prim@char
1441 /// [pattern]: self::pattern
1443 /// # Iterator behavior
1445 /// The returned iterator will not be double ended, because it is
1446 /// not efficient to support.
1448 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1451 /// [`rsplitn`]: str::rsplitn
1455 /// Simple patterns:
1458 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1459 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1461 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1462 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1464 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1465 /// assert_eq!(v, ["abcXdef"]);
1467 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1468 /// assert_eq!(v, [""]);
1471 /// A more complex pattern, using a closure:
1474 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1475 /// assert_eq!(v, ["abc", "defXghi"]);
1477 #[stable(feature = "rust1", since = "1.0.0")]
1479 pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> {
1480 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1483 /// An iterator over substrings of this string slice, separated by a
1484 /// pattern, starting from the end of the string, restricted to returning
1485 /// at most `n` items.
1487 /// If `n` substrings are returned, the last substring (the `n`th substring)
1488 /// will contain the remainder of the string.
1490 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1491 /// function or closure that determines if a character matches.
1493 /// [`char`]: prim@char
1494 /// [pattern]: self::pattern
1496 /// # Iterator behavior
1498 /// The returned iterator will not be double ended, because it is not
1499 /// efficient to support.
1501 /// For splitting from the front, the [`splitn`] method can be used.
1503 /// [`splitn`]: str::splitn
1507 /// Simple patterns:
1510 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1511 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1513 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1514 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1516 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1517 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1520 /// A more complex pattern, using a closure:
1523 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1524 /// assert_eq!(v, ["ghi", "abc1def"]);
1526 #[stable(feature = "rust1", since = "1.0.0")]
1528 pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P>
1530 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1532 RSplitN(self.splitn(n, pat).0)
1535 /// Splits the string on the first occurrence of the specified delimiter and
1536 /// returns prefix before delimiter and suffix after delimiter.
1541 /// assert_eq!("cfg".split_once('='), None);
1542 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
1543 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1545 #[stable(feature = "str_split_once", since = "1.52.0")]
1547 pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> {
1548 let (start, end) = delimiter.into_searcher(self).next_match()?;
1549 // SAFETY: `Searcher` is known to return valid indices.
1550 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1553 /// Splits the string on the last occurrence of the specified delimiter and
1554 /// returns prefix before delimiter and suffix after delimiter.
1559 /// assert_eq!("cfg".rsplit_once('='), None);
1560 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
1561 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1563 #[stable(feature = "str_split_once", since = "1.52.0")]
1565 pub fn rsplit_once<'a, P>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)>
1567 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1569 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
1570 // SAFETY: `Searcher` is known to return valid indices.
1571 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
1574 /// An iterator over the disjoint matches of a pattern within the given string
1577 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1578 /// function or closure that determines if a character matches.
1580 /// [`char`]: prim@char
1581 /// [pattern]: self::pattern
1583 /// # Iterator behavior
1585 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1586 /// allows a reverse search and forward/reverse search yields the same
1587 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1589 /// If the pattern allows a reverse search but its results might differ
1590 /// from a forward search, the [`rmatches`] method can be used.
1592 /// [`rmatches`]: str::matches
1599 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
1600 /// assert_eq!(v, ["abc", "abc", "abc"]);
1602 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
1603 /// assert_eq!(v, ["1", "2", "3"]);
1605 #[stable(feature = "str_matches", since = "1.2.0")]
1607 pub fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> {
1608 Matches(MatchesInternal(pat.into_searcher(self)))
1611 /// An iterator over the disjoint matches of a pattern within this string slice,
1612 /// yielded in reverse order.
1614 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1615 /// function or closure that determines if a character matches.
1617 /// [`char`]: prim@char
1618 /// [pattern]: self::pattern
1620 /// # Iterator behavior
1622 /// The returned iterator requires that the pattern supports a reverse
1623 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1624 /// search yields the same elements.
1626 /// For iterating from the front, the [`matches`] method can be used.
1628 /// [`matches`]: str::matches
1635 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
1636 /// assert_eq!(v, ["abc", "abc", "abc"]);
1638 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
1639 /// assert_eq!(v, ["3", "2", "1"]);
1641 #[stable(feature = "str_matches", since = "1.2.0")]
1643 pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P>
1645 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1647 RMatches(self.matches(pat).0)
1650 /// An iterator over the disjoint matches of a pattern within this string
1651 /// slice as well as the index that the match starts at.
1653 /// For matches of `pat` within `self` that overlap, only the indices
1654 /// corresponding to the first match are returned.
1656 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1657 /// function or closure that determines if a character matches.
1659 /// [`char`]: prim@char
1660 /// [pattern]: self::pattern
1662 /// # Iterator behavior
1664 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1665 /// allows a reverse search and forward/reverse search yields the same
1666 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1668 /// If the pattern allows a reverse search but its results might differ
1669 /// from a forward search, the [`rmatch_indices`] method can be used.
1671 /// [`rmatch_indices`]: str::rmatch_indices
1678 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
1679 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
1681 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
1682 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
1684 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
1685 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
1687 #[stable(feature = "str_match_indices", since = "1.5.0")]
1689 pub fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
1690 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
1693 /// An iterator over the disjoint matches of a pattern within `self`,
1694 /// yielded in reverse order along with the index of the match.
1696 /// For matches of `pat` within `self` that overlap, only the indices
1697 /// corresponding to the last match are returned.
1699 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1700 /// function or closure that determines if a character matches.
1702 /// [`char`]: prim@char
1703 /// [pattern]: self::pattern
1705 /// # Iterator behavior
1707 /// The returned iterator requires that the pattern supports a reverse
1708 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1709 /// search yields the same elements.
1711 /// For iterating from the front, the [`match_indices`] method can be used.
1713 /// [`match_indices`]: str::match_indices
1720 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
1721 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
1723 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
1724 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
1726 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
1727 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
1729 #[stable(feature = "str_match_indices", since = "1.5.0")]
1731 pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P>
1733 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
1735 RMatchIndices(self.match_indices(pat).0)
1738 /// Returns a string slice with leading and trailing whitespace removed.
1740 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1741 /// Core Property `White_Space`.
1748 /// let s = " Hello\tworld\t";
1750 /// assert_eq!("Hello\tworld", s.trim());
1753 #[must_use = "this returns the trimmed string as a slice, \
1754 without modifying the original"]
1755 #[stable(feature = "rust1", since = "1.0.0")]
1756 pub fn trim(&self) -> &str {
1757 self.trim_matches(|c: char| c.is_whitespace())
1760 /// Returns a string slice with leading whitespace removed.
1762 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1763 /// Core Property `White_Space`.
1765 /// # Text directionality
1767 /// A string is a sequence of bytes. `start` in this context means the first
1768 /// position of that byte string; for a left-to-right language like English or
1769 /// Russian, this will be left side, and for right-to-left languages like
1770 /// Arabic or Hebrew, this will be the right side.
1777 /// let s = " Hello\tworld\t";
1778 /// assert_eq!("Hello\tworld\t", s.trim_start());
1784 /// let s = " English ";
1785 /// assert!(Some('E') == s.trim_start().chars().next());
1787 /// let s = " עברית ";
1788 /// assert!(Some('ע') == s.trim_start().chars().next());
1791 #[must_use = "this returns the trimmed string as a new slice, \
1792 without modifying the original"]
1793 #[stable(feature = "trim_direction", since = "1.30.0")]
1794 pub fn trim_start(&self) -> &str {
1795 self.trim_start_matches(|c: char| c.is_whitespace())
1798 /// Returns a string slice with trailing whitespace removed.
1800 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1801 /// Core Property `White_Space`.
1803 /// # Text directionality
1805 /// A string is a sequence of bytes. `end` in this context means the last
1806 /// position of that byte string; for a left-to-right language like English or
1807 /// Russian, this will be right side, and for right-to-left languages like
1808 /// Arabic or Hebrew, this will be the left side.
1815 /// let s = " Hello\tworld\t";
1816 /// assert_eq!(" Hello\tworld", s.trim_end());
1822 /// let s = " English ";
1823 /// assert!(Some('h') == s.trim_end().chars().rev().next());
1825 /// let s = " עברית ";
1826 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
1829 #[must_use = "this returns the trimmed string as a new slice, \
1830 without modifying the original"]
1831 #[stable(feature = "trim_direction", since = "1.30.0")]
1832 pub fn trim_end(&self) -> &str {
1833 self.trim_end_matches(|c: char| c.is_whitespace())
1836 /// Returns a string slice with leading whitespace removed.
1838 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1839 /// Core Property `White_Space`.
1841 /// # Text directionality
1843 /// A string is a sequence of bytes. 'Left' in this context means the first
1844 /// position of that byte string; for a language like Arabic or Hebrew
1845 /// which are 'right to left' rather than 'left to right', this will be
1846 /// the _right_ side, not the left.
1853 /// let s = " Hello\tworld\t";
1855 /// assert_eq!("Hello\tworld\t", s.trim_left());
1861 /// let s = " English";
1862 /// assert!(Some('E') == s.trim_left().chars().next());
1864 /// let s = " עברית";
1865 /// assert!(Some('ע') == s.trim_left().chars().next());
1867 #[must_use = "this returns the trimmed string as a new slice, \
1868 without modifying the original"]
1870 #[stable(feature = "rust1", since = "1.0.0")]
1873 reason = "superseded by `trim_start`",
1874 suggestion = "trim_start"
1876 pub fn trim_left(&self) -> &str {
1880 /// Returns a string slice with trailing whitespace removed.
1882 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1883 /// Core Property `White_Space`.
1885 /// # Text directionality
1887 /// A string is a sequence of bytes. 'Right' in this context means the last
1888 /// position of that byte string; for a language like Arabic or Hebrew
1889 /// which are 'right to left' rather than 'left to right', this will be
1890 /// the _left_ side, not the right.
1897 /// let s = " Hello\tworld\t";
1899 /// assert_eq!(" Hello\tworld", s.trim_right());
1905 /// let s = "English ";
1906 /// assert!(Some('h') == s.trim_right().chars().rev().next());
1908 /// let s = "עברית ";
1909 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
1911 #[must_use = "this returns the trimmed string as a new slice, \
1912 without modifying the original"]
1914 #[stable(feature = "rust1", since = "1.0.0")]
1917 reason = "superseded by `trim_end`",
1918 suggestion = "trim_end"
1920 pub fn trim_right(&self) -> &str {
1924 /// Returns a string slice with all prefixes and suffixes that match a
1925 /// pattern repeatedly removed.
1927 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
1928 /// or closure that determines if a character matches.
1930 /// [`char`]: prim@char
1931 /// [pattern]: self::pattern
1935 /// Simple patterns:
1938 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
1939 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
1941 /// let x: &[_] = &['1', '2'];
1942 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
1945 /// A more complex pattern, using a closure:
1948 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1950 #[must_use = "this returns the trimmed string as a new slice, \
1951 without modifying the original"]
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
1955 P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>,
1959 let mut matcher = pat.into_searcher(self);
1960 if let Some((a, b)) = matcher.next_reject() {
1962 j = b; // Remember earliest known match, correct it below if
1963 // last match is different
1965 if let Some((_, b)) = matcher.next_reject_back() {
1968 // SAFETY: `Searcher` is known to return valid indices.
1969 unsafe { self.get_unchecked(i..j) }
1972 /// Returns a string slice with all prefixes that match a pattern
1973 /// repeatedly removed.
1975 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1976 /// function or closure that determines if a character matches.
1978 /// [`char`]: prim@char
1979 /// [pattern]: self::pattern
1981 /// # Text directionality
1983 /// A string is a sequence of bytes. `start` in this context means the first
1984 /// position of that byte string; for a left-to-right language like English or
1985 /// Russian, this will be left side, and for right-to-left languages like
1986 /// Arabic or Hebrew, this will be the right side.
1993 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
1994 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
1996 /// let x: &[_] = &['1', '2'];
1997 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1999 #[must_use = "this returns the trimmed string as a new slice, \
2000 without modifying the original"]
2001 #[stable(feature = "trim_direction", since = "1.30.0")]
2002 pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2003 let mut i = self.len();
2004 let mut matcher = pat.into_searcher(self);
2005 if let Some((a, _)) = matcher.next_reject() {
2008 // SAFETY: `Searcher` is known to return valid indices.
2009 unsafe { self.get_unchecked(i..self.len()) }
2012 /// Returns a string slice with the prefix removed.
2014 /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped
2015 /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
2017 /// If the string does not start with `prefix`, returns `None`.
2019 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2020 /// function or closure that determines if a character matches.
2022 /// [`char`]: prim@char
2023 /// [pattern]: self::pattern
2028 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2029 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2030 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2032 #[must_use = "this returns the remaining substring as a new slice, \
2033 without modifying the original"]
2034 #[stable(feature = "str_strip", since = "1.45.0")]
2035 pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> {
2036 prefix.strip_prefix_of(self)
2039 /// Returns a string slice with the suffix removed.
2041 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2042 /// wrapped in `Some`. Unlike `trim_end_matches`, this method removes the suffix exactly once.
2044 /// If the string does not end with `suffix`, returns `None`.
2046 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2047 /// function or closure that determines if a character matches.
2049 /// [`char`]: prim@char
2050 /// [pattern]: self::pattern
2055 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2056 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2057 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2059 #[must_use = "this returns the remaining substring as a new slice, \
2060 without modifying the original"]
2061 #[stable(feature = "str_strip", since = "1.45.0")]
2062 pub fn strip_suffix<'a, P>(&'a self, suffix: P) -> Option<&'a str>
2065 <P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
2067 suffix.strip_suffix_of(self)
2070 /// Returns a string slice with all suffixes that match a pattern
2071 /// repeatedly removed.
2073 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2074 /// function or closure that determines if a character matches.
2076 /// [`char`]: prim@char
2077 /// [pattern]: self::pattern
2079 /// # Text directionality
2081 /// A string is a sequence of bytes. `end` in this context means the last
2082 /// position of that byte string; for a left-to-right language like English or
2083 /// Russian, this will be right side, and for right-to-left languages like
2084 /// Arabic or Hebrew, this will be the left side.
2088 /// Simple patterns:
2091 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2092 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2094 /// let x: &[_] = &['1', '2'];
2095 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2098 /// A more complex pattern, using a closure:
2101 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2103 #[must_use = "this returns the trimmed string as a new slice, \
2104 without modifying the original"]
2105 #[stable(feature = "trim_direction", since = "1.30.0")]
2106 pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str
2108 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2111 let mut matcher = pat.into_searcher(self);
2112 if let Some((_, b)) = matcher.next_reject_back() {
2115 // SAFETY: `Searcher` is known to return valid indices.
2116 unsafe { self.get_unchecked(0..j) }
2119 /// Returns a string slice with all prefixes that match a pattern
2120 /// repeatedly removed.
2122 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2123 /// function or closure that determines if a character matches.
2125 /// [`char`]: prim@char
2126 /// [pattern]: self::pattern
2128 /// # Text directionality
2130 /// A string is a sequence of bytes. 'Left' in this context means the first
2131 /// position of that byte string; for a language like Arabic or Hebrew
2132 /// which are 'right to left' rather than 'left to right', this will be
2133 /// the _right_ side, not the left.
2140 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2141 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2143 /// let x: &[_] = &['1', '2'];
2144 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2146 #[stable(feature = "rust1", since = "1.0.0")]
2149 reason = "superseded by `trim_start_matches`",
2150 suggestion = "trim_start_matches"
2152 pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
2153 self.trim_start_matches(pat)
2156 /// Returns a string slice with all suffixes that match a pattern
2157 /// repeatedly removed.
2159 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2160 /// function or closure that determines if a character matches.
2162 /// [`char`]: prim@char
2163 /// [pattern]: self::pattern
2165 /// # Text directionality
2167 /// A string is a sequence of bytes. 'Right' in this context means the last
2168 /// position of that byte string; for a language like Arabic or Hebrew
2169 /// which are 'right to left' rather than 'left to right', this will be
2170 /// the _left_ side, not the right.
2174 /// Simple patterns:
2177 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2178 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2180 /// let x: &[_] = &['1', '2'];
2181 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2184 /// A more complex pattern, using a closure:
2187 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2189 #[stable(feature = "rust1", since = "1.0.0")]
2192 reason = "superseded by `trim_end_matches`",
2193 suggestion = "trim_end_matches"
2195 pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str
2197 P: Pattern<'a, Searcher: ReverseSearcher<'a>>,
2199 self.trim_end_matches(pat)
2202 /// Parses this string slice into another type.
2204 /// Because `parse` is so general, it can cause problems with type
2205 /// inference. As such, `parse` is one of the few times you'll see
2206 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2207 /// helps the inference algorithm understand specifically which type
2208 /// you're trying to parse into.
2210 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2215 /// Will return [`Err`] if it's not possible to parse this string slice into
2216 /// the desired type.
2218 /// [`Err`]: FromStr::Err
2225 /// let four: u32 = "4".parse().unwrap();
2227 /// assert_eq!(4, four);
2230 /// Using the 'turbofish' instead of annotating `four`:
2233 /// let four = "4".parse::<u32>();
2235 /// assert_eq!(Ok(4), four);
2238 /// Failing to parse:
2241 /// let nope = "j".parse::<u32>();
2243 /// assert!(nope.is_err());
2246 #[stable(feature = "rust1", since = "1.0.0")]
2247 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2248 FromStr::from_str(self)
2251 /// Checks if all characters in this string are within the ASCII range.
2256 /// let ascii = "hello!\n";
2257 /// let non_ascii = "Grüße, Jürgen ❤";
2259 /// assert!(ascii.is_ascii());
2260 /// assert!(!non_ascii.is_ascii());
2262 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2265 pub fn is_ascii(&self) -> bool {
2266 // We can treat each byte as character here: all multibyte characters
2267 // start with a byte that is not in the ascii range, so we will stop
2269 self.as_bytes().is_ascii()
2272 /// Checks that two strings are an ASCII case-insensitive match.
2274 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2275 /// but without allocating and copying temporaries.
2280 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2281 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2282 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2284 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2287 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2288 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2291 /// Converts this string to its ASCII upper case equivalent in-place.
2293 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2294 /// but non-ASCII letters are unchanged.
2296 /// To return a new uppercased value without modifying the existing one, use
2297 /// [`to_ascii_uppercase()`].
2299 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2304 /// let mut s = String::from("Grüße, Jürgen ❤");
2306 /// s.make_ascii_uppercase();
2308 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2310 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2312 pub fn make_ascii_uppercase(&mut self) {
2313 // SAFETY: safe because we transmute two types with the same layout.
2314 let me = unsafe { self.as_bytes_mut() };
2315 me.make_ascii_uppercase()
2318 /// Converts this string to its ASCII lower case equivalent in-place.
2320 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2321 /// but non-ASCII letters are unchanged.
2323 /// To return a new lowercased value without modifying the existing one, use
2324 /// [`to_ascii_lowercase()`].
2326 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2331 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2333 /// s.make_ascii_lowercase();
2335 /// assert_eq!("grÜße, jÜrgen ❤", s);
2337 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2339 pub fn make_ascii_lowercase(&mut self) {
2340 // SAFETY: safe because we transmute two types with the same layout.
2341 let me = unsafe { self.as_bytes_mut() };
2342 me.make_ascii_lowercase()
2345 /// Return an iterator that escapes each char in `self` with [`char::escape_debug`].
2347 /// Note: only extended grapheme codepoints that begin the string will be
2355 /// for c in "❤\n!".escape_debug() {
2356 /// print!("{}", c);
2361 /// Using `println!` directly:
2364 /// println!("{}", "❤\n!".escape_debug());
2368 /// Both are equivalent to:
2371 /// println!("❤\\n!");
2374 /// Using `to_string`:
2377 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
2379 #[must_use = "this returns the escaped string as an iterator, \
2380 without modifying the original"]
2381 #[stable(feature = "str_escape", since = "1.34.0")]
2382 pub fn escape_debug(&self) -> EscapeDebug<'_> {
2383 let mut chars = self.chars();
2387 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
2390 .chain(chars.flat_map(CharEscapeDebugContinue)),
2394 /// Return an iterator that escapes each char in `self` with [`char::escape_default`].
2401 /// for c in "❤\n!".escape_default() {
2402 /// print!("{}", c);
2407 /// Using `println!` directly:
2410 /// println!("{}", "❤\n!".escape_default());
2414 /// Both are equivalent to:
2417 /// println!("\\u{{2764}}\\n!");
2420 /// Using `to_string`:
2423 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
2425 #[must_use = "this returns the escaped string as an iterator, \
2426 without modifying the original"]
2427 #[stable(feature = "str_escape", since = "1.34.0")]
2428 pub fn escape_default(&self) -> EscapeDefault<'_> {
2429 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
2432 /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`].
2439 /// for c in "❤\n!".escape_unicode() {
2440 /// print!("{}", c);
2445 /// Using `println!` directly:
2448 /// println!("{}", "❤\n!".escape_unicode());
2452 /// Both are equivalent to:
2455 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
2458 /// Using `to_string`:
2461 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
2463 #[must_use = "this returns the escaped string as an iterator, \
2464 without modifying the original"]
2465 #[stable(feature = "str_escape", since = "1.34.0")]
2466 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
2467 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 impl AsRef<[u8]> for str {
2474 fn as_ref(&self) -> &[u8] {
2479 #[stable(feature = "rust1", since = "1.0.0")]
2480 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2481 impl const Default for &str {
2482 /// Creates an empty str
2484 fn default() -> Self {
2489 #[stable(feature = "default_mut_str", since = "1.28.0")]
2490 impl Default for &mut str {
2491 /// Creates an empty mutable str
2493 fn default() -> Self {
2494 // SAFETY: The empty string is valid UTF-8.
2495 unsafe { from_utf8_unchecked_mut(&mut []) }
2500 /// A nameable, cloneable fn type
2502 struct LinesAnyMap impl<'a> Fn = |line: &'a str| -> &'a str {
2504 if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] }
2509 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
2510 c.escape_debug_ext(EscapeDebugExtArgs {
2511 escape_grapheme_extended: false,
2512 escape_single_quote: true,
2513 escape_double_quote: true
2518 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
2522 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
2527 struct IsWhitespace impl Fn = |c: char| -> bool {
2532 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
2533 byte.is_ascii_whitespace()
2537 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
2542 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
2547 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
2549 unsafe { from_utf8_unchecked(bytes) }